3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2016 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2016-10-03T18:59:01Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
64 * Generate a unique ID for element
66 * @return {string} [id]
68 OO
.ui
.generateElementId = function () {
70 return 'oojsui-' + OO
.ui
.elementId
;
74 * Check if an element is focusable.
75 * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14
77 * @param {jQuery} $element Element to test
80 OO
.ui
.isFocusableElement = function ( $element
) {
82 element
= $element
[ 0 ];
84 // Anything disabled is not focusable
85 if ( element
.disabled
) {
89 // Check if the element is visible
91 // This is quicker than calling $element.is( ':visible' )
92 $.expr
.filters
.visible( element
) &&
93 // Check that all parents are visible
94 !$element
.parents().addBack().filter( function () {
95 return $.css( this, 'visibility' ) === 'hidden';
101 // Check if the element is ContentEditable, which is the string 'true'
102 if ( element
.contentEditable
=== 'true' ) {
106 // Anything with a non-negative numeric tabIndex is focusable.
107 // Use .prop to avoid browser bugs
108 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
112 // Some element types are naturally focusable
113 // (indexOf is much faster than regex in Chrome and about the
114 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
115 nodeName
= element
.nodeName
.toLowerCase();
116 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
120 // Links and areas are focusable if they have an href
121 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
129 * Find a focusable child
131 * @param {jQuery} $container Container to search in
132 * @param {boolean} [backwards] Search backwards
133 * @return {jQuery} Focusable child, an empty jQuery object if none found
135 OO
.ui
.findFocusable = function ( $container
, backwards
) {
136 var $focusable
= $( [] ),
137 // $focusableCandidates is a superset of things that
138 // could get matched by isFocusableElement
139 $focusableCandidates
= $container
140 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
143 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
146 $focusableCandidates
.each( function () {
147 var $this = $( this );
148 if ( OO
.ui
.isFocusableElement( $this ) ) {
157 * Get the user's language and any fallback languages.
159 * These language codes are used to localize user interface elements in the user's language.
161 * In environments that provide a localization system, this function should be overridden to
162 * return the user's language(s). The default implementation returns English (en) only.
164 * @return {string[]} Language codes, in descending order of priority
166 OO
.ui
.getUserLanguages = function () {
171 * Get a value in an object keyed by language code.
173 * @param {Object.<string,Mixed>} obj Object keyed by language code
174 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
175 * @param {string} [fallback] Fallback code, used if no matching language can be found
176 * @return {Mixed} Local value
178 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
181 // Requested language
185 // Known user language
186 langs
= OO
.ui
.getUserLanguages();
187 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
194 if ( obj
[ fallback
] ) {
195 return obj
[ fallback
];
197 // First existing language
198 for ( lang
in obj
) {
206 * Check if a node is contained within another node
208 * Similar to jQuery#contains except a list of containers can be supplied
209 * and a boolean argument allows you to include the container in the match list
211 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
212 * @param {HTMLElement} contained Node to find
213 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
214 * @return {boolean} The node is in the list of target nodes
216 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
218 if ( !Array
.isArray( containers
) ) {
219 containers
= [ containers
];
221 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
222 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
230 * Return a function, that, as long as it continues to be invoked, will not
231 * be triggered. The function will be called after it stops being called for
232 * N milliseconds. If `immediate` is passed, trigger the function on the
233 * leading edge, instead of the trailing.
235 * Ported from: http://underscorejs.org/underscore.js
237 * @param {Function} func
238 * @param {number} wait
239 * @param {boolean} immediate
242 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
247 later = function () {
250 func
.apply( context
, args
);
253 if ( immediate
&& !timeout
) {
254 func
.apply( context
, args
);
256 if ( !timeout
|| wait
) {
257 clearTimeout( timeout
);
258 timeout
= setTimeout( later
, wait
);
264 * Returns a function, that, when invoked, will only be triggered at most once
265 * during a given window of time. If called again during that window, it will
266 * wait until the window ends and then trigger itself again.
268 * As it's not knowable to the caller whether the function will actually run
269 * when the wrapper is called, return values from the function are entirely
272 * @param {Function} func
273 * @param {number} wait
276 OO
.ui
.throttle = function ( func
, wait
) {
277 var context
, args
, timeout
,
281 previous
= OO
.ui
.now();
282 func
.apply( context
, args
);
285 // Check how long it's been since the last time the function was
286 // called, and whether it's more or less than the requested throttle
287 // period. If it's less, run the function immediately. If it's more,
288 // set a timeout for the remaining time -- but don't replace an
289 // existing timeout, since that'd indefinitely prolong the wait.
290 var remaining
= wait
- ( OO
.ui
.now() - previous
);
293 if ( remaining
<= 0 ) {
294 // Note: unless wait was ridiculously large, this means we'll
295 // automatically run the first time the function was called in a
296 // given period. (If you provide a wait period larger than the
297 // current Unix timestamp, you *deserve* unexpected behavior.)
298 clearTimeout( timeout
);
300 } else if ( !timeout
) {
301 timeout
= setTimeout( run
, remaining
);
307 * A (possibly faster) way to get the current timestamp as an integer
309 * @return {number} Current timestamp
311 OO
.ui
.now
= Date
.now
|| function () {
312 return new Date().getTime();
316 * Proxy for `node.addEventListener( eventName, handler, true )`.
318 * @param {HTMLElement} node
319 * @param {string} eventName
320 * @param {Function} handler
321 * @deprecated since 0.15.0
323 OO
.ui
.addCaptureEventListener = function ( node
, eventName
, handler
) {
324 node
.addEventListener( eventName
, handler
, true );
328 * Proxy for `node.removeEventListener( eventName, handler, true )`.
330 * @param {HTMLElement} node
331 * @param {string} eventName
332 * @param {Function} handler
333 * @deprecated since 0.15.0
335 OO
.ui
.removeCaptureEventListener = function ( node
, eventName
, handler
) {
336 node
.removeEventListener( eventName
, handler
, true );
340 * Reconstitute a JavaScript object corresponding to a widget created by
341 * the PHP implementation.
343 * This is an alias for `OO.ui.Element.static.infuse()`.
345 * @param {string|HTMLElement|jQuery} idOrNode
346 * A DOM id (if a string) or node for the widget to infuse.
347 * @return {OO.ui.Element}
348 * The `OO.ui.Element` corresponding to this (infusable) document node.
350 OO
.ui
.infuse = function ( idOrNode
) {
351 return OO
.ui
.Element
.static.infuse( idOrNode
);
356 * Message store for the default implementation of OO.ui.msg
358 * Environments that provide a localization system should not use this, but should override
359 * OO.ui.msg altogether.
364 // Tool tip for a button that moves items in a list down one place
365 'ooui-outline-control-move-down': 'Move item down',
366 // Tool tip for a button that moves items in a list up one place
367 'ooui-outline-control-move-up': 'Move item up',
368 // Tool tip for a button that removes items from a list
369 'ooui-outline-control-remove': 'Remove item',
370 // Label for the toolbar group that contains a list of all other available tools
371 'ooui-toolbar-more': 'More',
372 // Label for the fake tool that expands the full list of tools in a toolbar group
373 'ooui-toolgroup-expand': 'More',
374 // Label for the fake tool that collapses the full list of tools in a toolbar group
375 'ooui-toolgroup-collapse': 'Fewer',
376 // Default label for the accept button of a confirmation dialog
377 'ooui-dialog-message-accept': 'OK',
378 // Default label for the reject button of a confirmation dialog
379 'ooui-dialog-message-reject': 'Cancel',
380 // Title for process dialog error description
381 'ooui-dialog-process-error': 'Something went wrong',
382 // Label for process dialog dismiss error button, visible when describing errors
383 'ooui-dialog-process-dismiss': 'Dismiss',
384 // Label for process dialog retry action button, visible when describing only recoverable errors
385 'ooui-dialog-process-retry': 'Try again',
386 // Label for process dialog retry action button, visible when describing only warnings
387 'ooui-dialog-process-continue': 'Continue',
388 // Label for the file selection widget's select file button
389 'ooui-selectfile-button-select': 'Select a file',
390 // Label for the file selection widget if file selection is not supported
391 'ooui-selectfile-not-supported': 'File selection is not supported',
392 // Label for the file selection widget when no file is currently selected
393 'ooui-selectfile-placeholder': 'No file is selected',
394 // Label for the file selection widget's drop target
395 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
399 * Get a localized message.
401 * In environments that provide a localization system, this function should be overridden to
402 * return the message translated in the user's language. The default implementation always returns
405 * After the message key, message parameters may optionally be passed. In the default implementation,
406 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
407 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
408 * they support unnamed, ordered message parameters.
410 * @param {string} key Message key
411 * @param {...Mixed} [params] Message parameters
412 * @return {string} Translated message with parameters substituted
414 OO
.ui
.msg = function ( key
) {
415 var message
= messages
[ key
],
416 params
= Array
.prototype.slice
.call( arguments
, 1 );
417 if ( typeof message
=== 'string' ) {
418 // Perform $1 substitution
419 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
420 var i
= parseInt( n
, 10 );
421 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
424 // Return placeholder if message not found
425 message
= '[' + key
+ ']';
432 * Package a message and arguments for deferred resolution.
434 * Use this when you are statically specifying a message and the message may not yet be present.
436 * @param {string} key Message key
437 * @param {...Mixed} [params] Message parameters
438 * @return {Function} Function that returns the resolved message when executed
440 OO
.ui
.deferMsg = function () {
441 var args
= arguments
;
443 return OO
.ui
.msg
.apply( OO
.ui
, args
);
450 * If the message is a function it will be executed, otherwise it will pass through directly.
452 * @param {Function|string} msg Deferred message, or message text
453 * @return {string} Resolved message
455 OO
.ui
.resolveMsg = function ( msg
) {
456 if ( $.isFunction( msg
) ) {
463 * @param {string} url
466 OO
.ui
.isSafeUrl = function ( url
) {
467 // Keep this function in sync with php/Tag.php
468 var i
, protocolWhitelist
;
470 function stringStartsWith( haystack
, needle
) {
471 return haystack
.substr( 0, needle
.length
) === needle
;
474 protocolWhitelist
= [
475 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
476 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
477 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
484 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
485 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
490 // This matches '//' too
491 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
494 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
506 * Namespace for OOjs UI mixins.
508 * Mixins are named according to the type of object they are intended to
509 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
510 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
511 * is intended to be mixed in to an instance of OO.ui.Widget.
519 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
520 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
521 * connected to them and can't be interacted with.
527 * @param {Object} [config] Configuration options
528 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
529 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
531 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
532 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
533 * @cfg {string} [text] Text to insert
534 * @cfg {Array} [content] An array of content elements to append (after #text).
535 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
536 * Instances of OO.ui.Element will have their $element appended.
537 * @cfg {jQuery} [$content] Content elements to append (after #text).
538 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
539 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
540 * Data can also be specified with the #setData method.
542 OO
.ui
.Element
= function OoUiElement( config
) {
543 // Configuration initialization
544 config
= config
|| {};
549 this.data
= config
.data
;
550 this.$element
= config
.$element
||
551 $( document
.createElement( this.getTagName() ) );
552 this.elementGroup
= null;
553 this.debouncedUpdateThemeClassesHandler
= OO
.ui
.debounce( this.debouncedUpdateThemeClasses
);
556 if ( Array
.isArray( config
.classes
) ) {
557 this.$element
.addClass( config
.classes
.join( ' ' ) );
560 this.$element
.attr( 'id', config
.id
);
563 this.$element
.text( config
.text
);
565 if ( config
.content
) {
566 // The `content` property treats plain strings as text; use an
567 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
568 // appropriate $element appended.
569 this.$element
.append( config
.content
.map( function ( v
) {
570 if ( typeof v
=== 'string' ) {
571 // Escape string so it is properly represented in HTML.
572 return document
.createTextNode( v
);
573 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
576 } else if ( v
instanceof OO
.ui
.Element
) {
582 if ( config
.$content
) {
583 // The `$content` property treats plain strings as HTML.
584 this.$element
.append( config
.$content
);
590 OO
.initClass( OO
.ui
.Element
);
592 /* Static Properties */
595 * The name of the HTML tag used by the element.
597 * The static value may be ignored if the #getTagName method is overridden.
603 OO
.ui
.Element
.static.tagName
= 'div';
608 * Reconstitute a JavaScript object corresponding to a widget created
609 * by the PHP implementation.
611 * @param {string|HTMLElement|jQuery} idOrNode
612 * A DOM id (if a string) or node for the widget to infuse.
613 * @return {OO.ui.Element}
614 * The `OO.ui.Element` corresponding to this (infusable) document node.
615 * For `Tag` objects emitted on the HTML side (used occasionally for content)
616 * the value returned is a newly-created Element wrapping around the existing
619 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
620 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
621 // Verify that the type matches up.
622 // FIXME: uncomment after T89721 is fixed (see T90929)
624 if ( !( obj instanceof this['class'] ) ) {
625 throw new Error( 'Infusion type mismatch!' );
632 * Implementation helper for `infuse`; skips the type check and has an
633 * extra property so that only the top-level invocation touches the DOM.
636 * @param {string|HTMLElement|jQuery} idOrNode
637 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
638 * when the top-level widget of this infusion is inserted into DOM,
639 * replacing the original node; or false for top-level invocation.
640 * @return {OO.ui.Element}
642 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
643 // look for a cached result of a previous infusion.
644 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
645 if ( typeof idOrNode
=== 'string' ) {
647 $elem
= $( document
.getElementById( id
) );
649 $elem
= $( idOrNode
);
650 id
= $elem
.attr( 'id' );
652 if ( !$elem
.length
) {
653 throw new Error( 'Widget not found: ' + id
);
655 if ( $elem
[ 0 ].oouiInfused
) {
656 $elem
= $elem
[ 0 ].oouiInfused
;
658 data
= $elem
.data( 'ooui-infused' );
661 if ( data
=== true ) {
662 throw new Error( 'Circular dependency! ' + id
);
665 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
666 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
667 // restore dynamic state after the new element is re-inserted into DOM under infused parent
668 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
669 infusedChildren
= $elem
.data( 'ooui-infused-children' );
670 if ( infusedChildren
&& infusedChildren
.length
) {
671 infusedChildren
.forEach( function ( data
) {
672 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
673 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
679 data
= $elem
.attr( 'data-ooui' );
681 throw new Error( 'No infusion data found: ' + id
);
684 data
= $.parseJSON( data
);
688 if ( !( data
&& data
._
) ) {
689 throw new Error( 'No valid infusion data found: ' + id
);
691 if ( data
._
=== 'Tag' ) {
692 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
693 return new OO
.ui
.Element( { $element
: $elem
} );
695 parts
= data
._
.split( '.' );
696 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
697 if ( cls
=== undefined ) {
698 // The PHP output might be old and not including the "OO.ui" prefix
699 // TODO: Remove this back-compat after next major release
700 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
701 if ( cls
=== undefined ) {
702 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
706 // Verify that we're creating an OO.ui.Element instance
709 while ( parent
!== undefined ) {
710 if ( parent
=== OO
.ui
.Element
) {
715 parent
= parent
.parent
;
718 if ( parent
!== OO
.ui
.Element
) {
719 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
722 if ( domPromise
=== false ) {
724 domPromise
= top
.promise();
726 $elem
.data( 'ooui-infused', true ); // prevent loops
727 data
.id
= id
; // implicit
728 infusedChildren
= [];
729 data
= OO
.copy( data
, null, function deserialize( value
) {
731 if ( OO
.isPlainObject( value
) ) {
733 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
734 infusedChildren
.push( infused
);
735 // Flatten the structure
736 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
737 infused
.$element
.removeData( 'ooui-infused-children' );
740 if ( value
.html
!== undefined ) {
741 return new OO
.ui
.HtmlSnippet( value
.html
);
745 // allow widgets to reuse parts of the DOM
746 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
747 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
748 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
750 obj
= new cls( data
);
751 // now replace old DOM with this new DOM.
753 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
754 // so only mutate the DOM if we need to.
755 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
756 $elem
.replaceWith( obj
.$element
);
757 // This element is now gone from the DOM, but if anyone is holding a reference to it,
758 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
759 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
760 $elem
[ 0 ].oouiInfused
= obj
.$element
;
764 obj
.$element
.data( 'ooui-infused', obj
);
765 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
766 // set the 'data-ooui' attribute so we can identify infused widgets
767 obj
.$element
.attr( 'data-ooui', '' );
768 // restore dynamic state after the new element is inserted into DOM
769 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
774 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
776 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
777 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
778 * constructor, which will be given the enhanced config.
781 * @param {HTMLElement} node
782 * @param {Object} config
785 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
790 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node
791 * (and its children) that represent an Element of the same class and the given configuration,
792 * generated by the PHP implementation.
794 * This method is called just before `node` is detached from the DOM. The return value of this
795 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
796 * is inserted into DOM to replace `node`.
799 * @param {HTMLElement} node
800 * @param {Object} config
803 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
808 * Get a jQuery function within a specific document.
811 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
812 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
814 * @return {Function} Bound jQuery function
816 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
817 function wrapper( selector
) {
818 return $( selector
, wrapper
.context
);
821 wrapper
.context
= this.getDocument( context
);
824 wrapper
.$iframe
= $iframe
;
831 * Get the document of an element.
834 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
835 * @return {HTMLDocument|null} Document object
837 OO
.ui
.Element
.static.getDocument = function ( obj
) {
838 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
839 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
840 // Empty jQuery selections might have a context
847 ( obj
.nodeType
=== 9 && obj
) ||
852 * Get the window of an element or document.
855 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
856 * @return {Window} Window object
858 OO
.ui
.Element
.static.getWindow = function ( obj
) {
859 var doc
= this.getDocument( obj
);
860 return doc
.defaultView
;
864 * Get the direction of an element or document.
867 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
868 * @return {string} Text direction, either 'ltr' or 'rtl'
870 OO
.ui
.Element
.static.getDir = function ( obj
) {
873 if ( obj
instanceof jQuery
) {
876 isDoc
= obj
.nodeType
=== 9;
877 isWin
= obj
.document
!== undefined;
878 if ( isDoc
|| isWin
) {
884 return $( obj
).css( 'direction' );
888 * Get the offset between two frames.
890 * TODO: Make this function not use recursion.
893 * @param {Window} from Window of the child frame
894 * @param {Window} [to=window] Window of the parent frame
895 * @param {Object} [offset] Offset to start with, used internally
896 * @return {Object} Offset object, containing left and top properties
898 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
899 var i
, len
, frames
, frame
, rect
;
905 offset
= { top
: 0, left
: 0 };
907 if ( from.parent
=== from ) {
911 // Get iframe element
912 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
913 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
914 if ( frames
[ i
].contentWindow
=== from ) {
920 // Recursively accumulate offset values
922 rect
= frame
.getBoundingClientRect();
923 offset
.left
+= rect
.left
;
924 offset
.top
+= rect
.top
;
926 this.getFrameOffset( from.parent
, offset
);
933 * Get the offset between two elements.
935 * The two elements may be in a different frame, but in that case the frame $element is in must
936 * be contained in the frame $anchor is in.
939 * @param {jQuery} $element Element whose position to get
940 * @param {jQuery} $anchor Element to get $element's position relative to
941 * @return {Object} Translated position coordinates, containing top and left properties
943 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
944 var iframe
, iframePos
,
945 pos
= $element
.offset(),
946 anchorPos
= $anchor
.offset(),
947 elementDocument
= this.getDocument( $element
),
948 anchorDocument
= this.getDocument( $anchor
);
950 // If $element isn't in the same document as $anchor, traverse up
951 while ( elementDocument
!== anchorDocument
) {
952 iframe
= elementDocument
.defaultView
.frameElement
;
954 throw new Error( '$element frame is not contained in $anchor frame' );
956 iframePos
= $( iframe
).offset();
957 pos
.left
+= iframePos
.left
;
958 pos
.top
+= iframePos
.top
;
959 elementDocument
= iframe
.ownerDocument
;
961 pos
.left
-= anchorPos
.left
;
962 pos
.top
-= anchorPos
.top
;
967 * Get element border sizes.
970 * @param {HTMLElement} el Element to measure
971 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
973 OO
.ui
.Element
.static.getBorders = function ( el
) {
974 var doc
= el
.ownerDocument
,
975 win
= doc
.defaultView
,
976 style
= win
.getComputedStyle( el
, null ),
978 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
979 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
980 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
981 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
992 * Get dimensions of an element or window.
995 * @param {HTMLElement|Window} el Element to measure
996 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
998 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1000 doc
= el
.ownerDocument
|| el
.document
,
1001 win
= doc
.defaultView
;
1003 if ( win
=== el
|| el
=== doc
.documentElement
) {
1006 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1008 top
: $win
.scrollTop(),
1009 left
: $win
.scrollLeft()
1011 scrollbar
: { right
: 0, bottom
: 0 },
1015 bottom
: $win
.innerHeight(),
1016 right
: $win
.innerWidth()
1022 borders
: this.getBorders( el
),
1024 top
: $el
.scrollTop(),
1025 left
: $el
.scrollLeft()
1028 right
: $el
.innerWidth() - el
.clientWidth
,
1029 bottom
: $el
.innerHeight() - el
.clientHeight
1031 rect
: el
.getBoundingClientRect()
1037 * Get scrollable object parent
1039 * documentElement can't be used to get or set the scrollTop
1040 * property on Blink. Changing and testing its value lets us
1041 * use 'body' or 'documentElement' based on what is working.
1043 * https://code.google.com/p/chromium/issues/detail?id=303131
1046 * @param {HTMLElement} el Element to find scrollable parent for
1047 * @return {HTMLElement} Scrollable parent
1049 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1050 var scrollTop
, body
;
1052 if ( OO
.ui
.scrollableElement
=== undefined ) {
1053 body
= el
.ownerDocument
.body
;
1054 scrollTop
= body
.scrollTop
;
1057 if ( body
.scrollTop
=== 1 ) {
1058 body
.scrollTop
= scrollTop
;
1059 OO
.ui
.scrollableElement
= 'body';
1061 OO
.ui
.scrollableElement
= 'documentElement';
1065 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1069 * Get closest scrollable container.
1071 * Traverses up until either a scrollable element or the root is reached, in which case the window
1075 * @param {HTMLElement} el Element to find scrollable container for
1076 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1077 * @return {HTMLElement} Closest scrollable container
1079 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1081 // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091
1082 props
= [ 'overflow-x', 'overflow-y' ],
1083 $parent
= $( el
).parent();
1085 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1086 props
= [ 'overflow-' + dimension
];
1089 while ( $parent
.length
) {
1090 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1091 return $parent
[ 0 ];
1095 val
= $parent
.css( props
[ i
] );
1096 if ( val
=== 'auto' || val
=== 'scroll' ) {
1097 return $parent
[ 0 ];
1100 $parent
= $parent
.parent();
1102 return this.getDocument( el
).body
;
1106 * Scroll element into view.
1109 * @param {HTMLElement} el Element to scroll into view
1110 * @param {Object} [config] Configuration options
1111 * @param {string} [config.duration='fast'] jQuery animation duration value
1112 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1113 * to scroll in both directions
1114 * @param {Function} [config.complete] Function to call when scrolling completes.
1115 * Deprecated since 0.15.4, use the return promise instead.
1116 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1118 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1119 var position
, animations
, callback
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1120 deferred
= $.Deferred();
1122 // Configuration initialization
1123 config
= config
|| {};
1126 callback
= typeof config
.complete
=== 'function' && config
.complete
;
1127 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1128 $container
= $( container
);
1129 elementDimensions
= this.getDimensions( el
);
1130 containerDimensions
= this.getDimensions( container
);
1131 $window
= $( this.getWindow( el
) );
1133 // Compute the element's position relative to the container
1134 if ( $container
.is( 'html, body' ) ) {
1135 // If the scrollable container is the root, this is easy
1137 top
: elementDimensions
.rect
.top
,
1138 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1139 left
: elementDimensions
.rect
.left
,
1140 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1143 // Otherwise, we have to subtract el's coordinates from container's coordinates
1145 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1146 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1147 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1148 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1152 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1153 if ( position
.top
< 0 ) {
1154 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1155 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1156 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1159 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1160 if ( position
.left
< 0 ) {
1161 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1162 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1163 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1166 if ( !$.isEmptyObject( animations
) ) {
1167 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1168 $container
.queue( function ( next
) {
1181 return deferred
.promise();
1185 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1186 * and reserve space for them, because it probably doesn't.
1188 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1189 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1190 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1191 * and then reattach (or show) them back.
1194 * @param {HTMLElement} el Element to reconsider the scrollbars on
1196 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1197 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1198 // Save scroll position
1199 scrollLeft
= el
.scrollLeft
;
1200 scrollTop
= el
.scrollTop
;
1201 // Detach all children
1202 while ( el
.firstChild
) {
1203 nodes
.push( el
.firstChild
);
1204 el
.removeChild( el
.firstChild
);
1207 void el
.offsetHeight
;
1208 // Reattach all children
1209 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1210 el
.appendChild( nodes
[ i
] );
1212 // Restore scroll position (no-op if scrollbars disappeared)
1213 el
.scrollLeft
= scrollLeft
;
1214 el
.scrollTop
= scrollTop
;
1220 * Toggle visibility of an element.
1222 * @param {boolean} [show] Make element visible, omit to toggle visibility
1226 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1227 show
= show
=== undefined ? !this.visible
: !!show
;
1229 if ( show
!== this.isVisible() ) {
1230 this.visible
= show
;
1231 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1232 this.emit( 'toggle', show
);
1239 * Check if element is visible.
1241 * @return {boolean} element is visible
1243 OO
.ui
.Element
.prototype.isVisible = function () {
1244 return this.visible
;
1250 * @return {Mixed} Element data
1252 OO
.ui
.Element
.prototype.getData = function () {
1259 * @param {Mixed} data Element data
1262 OO
.ui
.Element
.prototype.setData = function ( data
) {
1268 * Check if element supports one or more methods.
1270 * @param {string|string[]} methods Method or list of methods to check
1271 * @return {boolean} All methods are supported
1273 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1277 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1278 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1279 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1284 return methods
.length
=== support
;
1288 * Update the theme-provided classes.
1290 * @localdoc This is called in element mixins and widget classes any time state changes.
1291 * Updating is debounced, minimizing overhead of changing multiple attributes and
1292 * guaranteeing that theme updates do not occur within an element's constructor
1294 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1295 this.debouncedUpdateThemeClassesHandler();
1300 * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to
1301 * make them synchronous.
1303 OO
.ui
.Element
.prototype.debouncedUpdateThemeClasses = function () {
1304 OO
.ui
.theme
.updateElementClasses( this );
1308 * Get the HTML tag name.
1310 * Override this method to base the result on instance information.
1312 * @return {string} HTML tag name
1314 OO
.ui
.Element
.prototype.getTagName = function () {
1315 return this.constructor.static.tagName
;
1319 * Check if the element is attached to the DOM
1321 * @return {boolean} The element is attached to the DOM
1323 OO
.ui
.Element
.prototype.isElementAttached = function () {
1324 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1328 * Get the DOM document.
1330 * @return {HTMLDocument} Document object
1332 OO
.ui
.Element
.prototype.getElementDocument = function () {
1333 // Don't cache this in other ways either because subclasses could can change this.$element
1334 return OO
.ui
.Element
.static.getDocument( this.$element
);
1338 * Get the DOM window.
1340 * @return {Window} Window object
1342 OO
.ui
.Element
.prototype.getElementWindow = function () {
1343 return OO
.ui
.Element
.static.getWindow( this.$element
);
1347 * Get closest scrollable container.
1349 * @return {HTMLElement} Closest scrollable container
1351 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1352 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1356 * Get group element is in.
1358 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1360 OO
.ui
.Element
.prototype.getElementGroup = function () {
1361 return this.elementGroup
;
1365 * Set group element is in.
1367 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1370 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1371 this.elementGroup
= group
;
1376 * Scroll element into view.
1378 * @param {Object} [config] Configuration options
1379 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1381 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1382 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1386 * Restore the pre-infusion dynamic state for this widget.
1388 * This method is called after #$element has been inserted into DOM. The parameter is the return
1389 * value of #gatherPreInfuseState.
1392 * @param {Object} state
1394 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1398 * Wraps an HTML snippet for use with configuration values which default
1399 * to strings. This bypasses the default html-escaping done to string
1405 * @param {string} [content] HTML content
1407 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1409 this.content
= content
;
1414 OO
.initClass( OO
.ui
.HtmlSnippet
);
1421 * @return {string} Unchanged HTML snippet.
1423 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1424 return this.content
;
1428 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1429 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1430 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1431 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1432 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1436 * @extends OO.ui.Element
1437 * @mixins OO.EventEmitter
1440 * @param {Object} [config] Configuration options
1442 OO
.ui
.Layout
= function OoUiLayout( config
) {
1443 // Configuration initialization
1444 config
= config
|| {};
1446 // Parent constructor
1447 OO
.ui
.Layout
.parent
.call( this, config
);
1449 // Mixin constructors
1450 OO
.EventEmitter
.call( this );
1453 this.$element
.addClass( 'oo-ui-layout' );
1458 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1459 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1462 * Widgets are compositions of one or more OOjs UI elements that users can both view
1463 * and interact with. All widgets can be configured and modified via a standard API,
1464 * and their state can change dynamically according to a model.
1468 * @extends OO.ui.Element
1469 * @mixins OO.EventEmitter
1472 * @param {Object} [config] Configuration options
1473 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1474 * appearance reflects this state.
1476 OO
.ui
.Widget
= function OoUiWidget( config
) {
1477 // Initialize config
1478 config
= $.extend( { disabled
: false }, config
);
1480 // Parent constructor
1481 OO
.ui
.Widget
.parent
.call( this, config
);
1483 // Mixin constructors
1484 OO
.EventEmitter
.call( this );
1487 this.disabled
= null;
1488 this.wasDisabled
= null;
1491 this.$element
.addClass( 'oo-ui-widget' );
1492 this.setDisabled( !!config
.disabled
);
1497 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1498 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1500 /* Static Properties */
1503 * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true,
1504 * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click
1509 * @property {boolean}
1511 OO
.ui
.Widget
.static.supportsSimpleLabel
= false;
1518 * A 'disable' event is emitted when the disabled state of the widget changes
1519 * (i.e. on disable **and** enable).
1521 * @param {boolean} disabled Widget is disabled
1527 * A 'toggle' event is emitted when the visibility of the widget changes.
1529 * @param {boolean} visible Widget is visible
1535 * Check if the widget is disabled.
1537 * @return {boolean} Widget is disabled
1539 OO
.ui
.Widget
.prototype.isDisabled = function () {
1540 return this.disabled
;
1544 * Set the 'disabled' state of the widget.
1546 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1548 * @param {boolean} disabled Disable widget
1551 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1554 this.disabled
= !!disabled
;
1555 isDisabled
= this.isDisabled();
1556 if ( isDisabled
!== this.wasDisabled
) {
1557 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1558 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1559 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1560 this.emit( 'disable', isDisabled
);
1561 this.updateThemeClasses();
1563 this.wasDisabled
= isDisabled
;
1569 * Update the disabled state, in case of changes in parent widget.
1573 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1574 this.setDisabled( this.disabled
);
1586 OO
.ui
.Theme
= function OoUiTheme() {};
1590 OO
.initClass( OO
.ui
.Theme
);
1595 * Get a list of classes to be applied to a widget.
1597 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1598 * otherwise state transitions will not work properly.
1600 * @param {OO.ui.Element} element Element for which to get classes
1601 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1603 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1604 return { on
: [], off
: [] };
1608 * Update CSS classes provided by the theme.
1610 * For elements with theme logic hooks, this should be called any time there's a state change.
1612 * @param {OO.ui.Element} element Element for which to update classes
1613 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1615 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1616 var $elements
= $( [] ),
1617 classes
= this.getElementClasses( element
);
1619 if ( element
.$icon
) {
1620 $elements
= $elements
.add( element
.$icon
);
1622 if ( element
.$indicator
) {
1623 $elements
= $elements
.add( element
.$indicator
);
1627 .removeClass( classes
.off
.join( ' ' ) )
1628 .addClass( classes
.on
.join( ' ' ) );
1632 * Get the transition duration in milliseconds for dialogs opening/closing
1634 * The dialog should be fully rendered this many milliseconds after the
1635 * ready process has executed.
1637 * @return {number} Transition duration in milliseconds
1639 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1644 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1645 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1646 * order in which users will navigate through the focusable elements via the "tab" key.
1649 * // TabIndexedElement is mixed into the ButtonWidget class
1650 * // to provide a tabIndex property.
1651 * var button1 = new OO.ui.ButtonWidget( {
1655 * var button2 = new OO.ui.ButtonWidget( {
1659 * var button3 = new OO.ui.ButtonWidget( {
1663 * var button4 = new OO.ui.ButtonWidget( {
1667 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1673 * @param {Object} [config] Configuration options
1674 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1675 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1676 * functionality will be applied to it instead.
1677 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1678 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1679 * to remove the element from the tab-navigation flow.
1681 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1682 // Configuration initialization
1683 config
= $.extend( { tabIndex
: 0 }, config
);
1686 this.$tabIndexed
= null;
1687 this.tabIndex
= null;
1690 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1693 this.setTabIndex( config
.tabIndex
);
1694 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1699 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1704 * Set the element that should use the tabindex functionality.
1706 * This method is used to retarget a tabindex mixin so that its functionality applies
1707 * to the specified element. If an element is currently using the functionality, the mixin’s
1708 * effect on that element is removed before the new element is set up.
1710 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1713 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1714 var tabIndex
= this.tabIndex
;
1715 // Remove attributes from old $tabIndexed
1716 this.setTabIndex( null );
1717 // Force update of new $tabIndexed
1718 this.$tabIndexed
= $tabIndexed
;
1719 this.tabIndex
= tabIndex
;
1720 return this.updateTabIndex();
1724 * Set the value of the tabindex.
1726 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1729 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1730 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1732 if ( this.tabIndex
!== tabIndex
) {
1733 this.tabIndex
= tabIndex
;
1734 this.updateTabIndex();
1741 * Update the `tabindex` attribute, in case of changes to tab index or
1747 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1748 if ( this.$tabIndexed
) {
1749 if ( this.tabIndex
!== null ) {
1750 // Do not index over disabled elements
1751 this.$tabIndexed
.attr( {
1752 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1753 // Support: ChromeVox and NVDA
1754 // These do not seem to inherit aria-disabled from parent elements
1755 'aria-disabled': this.isDisabled().toString()
1758 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1765 * Handle disable events.
1768 * @param {boolean} disabled Element is disabled
1770 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1771 this.updateTabIndex();
1775 * Get the value of the tabindex.
1777 * @return {number|null} Tabindex value
1779 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1780 return this.tabIndex
;
1784 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
1785 * interface element that can be configured with access keys for accessibility.
1786 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
1788 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
1794 * @param {Object} [config] Configuration options
1795 * @cfg {jQuery} [$button] The button element created by the class.
1796 * If this configuration is omitted, the button element will use a generated `<a>`.
1797 * @cfg {boolean} [framed=true] Render the button with a frame
1799 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
1800 // Configuration initialization
1801 config
= config
|| {};
1804 this.$button
= null;
1806 this.active
= config
.active
!== undefined && config
.active
;
1807 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
1808 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
1809 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
1810 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
1811 this.onClickHandler
= this.onClick
.bind( this );
1812 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
1815 this.$element
.addClass( 'oo-ui-buttonElement' );
1816 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
1817 this.setButtonElement( config
.$button
|| $( '<a>' ) );
1822 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
1824 /* Static Properties */
1827 * Cancel mouse down events.
1829 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
1830 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
1831 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
1836 * @property {boolean}
1838 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
1843 * A 'click' event is emitted when the button element is clicked.
1851 * Set the button element.
1853 * This method is used to retarget a button mixin so that its functionality applies to
1854 * the specified button element instead of the one created by the class. If a button element
1855 * is already set, the method will remove the mixin’s effect on that element.
1857 * @param {jQuery} $button Element to use as button
1859 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
1860 if ( this.$button
) {
1862 .removeClass( 'oo-ui-buttonElement-button' )
1863 .removeAttr( 'role accesskey' )
1865 mousedown
: this.onMouseDownHandler
,
1866 keydown
: this.onKeyDownHandler
,
1867 click
: this.onClickHandler
,
1868 keypress
: this.onKeyPressHandler
1872 this.$button
= $button
1873 .addClass( 'oo-ui-buttonElement-button' )
1874 .attr( { role
: 'button' } )
1876 mousedown
: this.onMouseDownHandler
,
1877 keydown
: this.onKeyDownHandler
,
1878 click
: this.onClickHandler
,
1879 keypress
: this.onKeyPressHandler
1884 * Handles mouse down events.
1887 * @param {jQuery.Event} e Mouse down event
1889 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
1890 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1893 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1894 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
1895 // reliably remove the pressed class
1896 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
1897 // Prevent change of focus unless specifically configured otherwise
1898 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
1904 * Handles mouse up events.
1907 * @param {MouseEvent} e Mouse up event
1909 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
1910 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
1913 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1914 // Stop listening for mouseup, since we only needed this once
1915 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
1919 * Handles mouse click events.
1922 * @param {jQuery.Event} e Mouse click event
1925 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
1926 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
1927 if ( this.emit( 'click' ) ) {
1934 * Handles key down events.
1937 * @param {jQuery.Event} e Key down event
1939 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
1940 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1943 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
1944 // Run the keyup handler no matter where the key is when the button is let go, so we can
1945 // reliably remove the pressed class
1946 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
1950 * Handles key up events.
1953 * @param {KeyboardEvent} e Key up event
1955 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
1956 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
1959 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
1960 // Stop listening for keyup, since we only needed this once
1961 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
1965 * Handles key press events.
1968 * @param {jQuery.Event} e Key press event
1971 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
1972 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
1973 if ( this.emit( 'click' ) ) {
1980 * Check if button has a frame.
1982 * @return {boolean} Button is framed
1984 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
1989 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
1991 * @param {boolean} [framed] Make button framed, omit to toggle
1994 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
1995 framed
= framed
=== undefined ? !this.framed
: !!framed
;
1996 if ( framed
!== this.framed
) {
1997 this.framed
= framed
;
1999 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2000 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2001 this.updateThemeClasses();
2008 * Set the button's active state.
2010 * The active state can be set on:
2012 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2013 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2014 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2017 * @param {boolean} value Make button active
2020 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2021 this.active
= !!value
;
2022 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2023 this.updateThemeClasses();
2028 * Check if the button is active
2031 * @return {boolean} The button is active
2033 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2038 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2039 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2040 * items from the group is done through the interface the class provides.
2041 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2043 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2049 * @param {Object} [config] Configuration options
2050 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2051 * is omitted, the group element will use a generated `<div>`.
2053 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2054 // Configuration initialization
2055 config
= config
|| {};
2060 this.aggregateItemEvents
= {};
2063 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2071 * A change event is emitted when the set of selected items changes.
2073 * @param {OO.ui.Element[]} items Items currently in the group
2079 * Set the group element.
2081 * If an element is already set, items will be moved to the new element.
2083 * @param {jQuery} $group Element to use as group
2085 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2088 this.$group
= $group
;
2089 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2090 this.$group
.append( this.items
[ i
].$element
);
2095 * Check if a group contains no items.
2097 * @return {boolean} Group is empty
2099 OO
.ui
.mixin
.GroupElement
.prototype.isEmpty = function () {
2100 return !this.items
.length
;
2104 * Get all items in the group.
2106 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
2107 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
2110 * @return {OO.ui.Element[]} An array of items.
2112 OO
.ui
.mixin
.GroupElement
.prototype.getItems = function () {
2113 return this.items
.slice( 0 );
2117 * Get an item by its data.
2119 * Only the first item with matching data will be returned. To return all matching items,
2120 * use the #getItemsFromData method.
2122 * @param {Object} data Item data to search for
2123 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2125 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2127 hash
= OO
.getHash( data
);
2129 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2130 item
= this.items
[ i
];
2131 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2140 * Get items by their data.
2142 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2144 * @param {Object} data Item data to search for
2145 * @return {OO.ui.Element[]} Items with equivalent data
2147 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2149 hash
= OO
.getHash( data
),
2152 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2153 item
= this.items
[ i
];
2154 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2163 * Aggregate the events emitted by the group.
2165 * When events are aggregated, the group will listen to all contained items for the event,
2166 * and then emit the event under a new name. The new event will contain an additional leading
2167 * parameter containing the item that emitted the original event. Other arguments emitted from
2168 * the original event are passed through.
2170 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
2171 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
2172 * A `null` value will remove aggregated events.
2174 * @throws {Error} An error is thrown if aggregation already exists.
2176 OO
.ui
.mixin
.GroupElement
.prototype.aggregate = function ( events
) {
2177 var i
, len
, item
, add
, remove
, itemEvent
, groupEvent
;
2179 for ( itemEvent
in events
) {
2180 groupEvent
= events
[ itemEvent
];
2182 // Remove existing aggregated event
2183 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2184 // Don't allow duplicate aggregations
2186 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
2188 // Remove event aggregation from existing items
2189 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2190 item
= this.items
[ i
];
2191 if ( item
.connect
&& item
.disconnect
) {
2193 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2194 item
.disconnect( this, remove
);
2197 // Prevent future items from aggregating event
2198 delete this.aggregateItemEvents
[ itemEvent
];
2201 // Add new aggregate event
2203 // Make future items aggregate event
2204 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
2205 // Add event aggregation to existing items
2206 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2207 item
= this.items
[ i
];
2208 if ( item
.connect
&& item
.disconnect
) {
2210 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
2211 item
.connect( this, add
);
2219 * Add items to the group.
2221 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2222 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2224 * @param {OO.ui.Element[]} items An array of items to add to the group
2225 * @param {number} [index] Index of the insertion point
2228 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2229 var i
, len
, item
, itemEvent
, events
, currentIndex
,
2232 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2235 // Check if item exists then remove it first, effectively "moving" it
2236 currentIndex
= this.items
.indexOf( item
);
2237 if ( currentIndex
>= 0 ) {
2238 this.removeItems( [ item
] );
2239 // Adjust index to compensate for removal
2240 if ( currentIndex
< index
) {
2245 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2247 for ( itemEvent
in this.aggregateItemEvents
) {
2248 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2250 item
.connect( this, events
);
2252 item
.setElementGroup( this );
2253 itemElements
.push( item
.$element
.get( 0 ) );
2256 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2257 this.$group
.append( itemElements
);
2258 this.items
.push
.apply( this.items
, items
);
2259 } else if ( index
=== 0 ) {
2260 this.$group
.prepend( itemElements
);
2261 this.items
.unshift
.apply( this.items
, items
);
2263 this.items
[ index
].$element
.before( itemElements
);
2264 this.items
.splice
.apply( this.items
, [ index
, 0 ].concat( items
) );
2267 this.emit( 'change', this.getItems() );
2272 * Remove the specified items from a group.
2274 * Removed items are detached (not removed) from the DOM so that they may be reused.
2275 * To remove all items from a group, you may wish to use the #clearItems method instead.
2277 * @param {OO.ui.Element[]} items An array of items to remove
2280 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2281 var i
, len
, item
, index
, events
, itemEvent
;
2283 // Remove specific items
2284 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2286 index
= this.items
.indexOf( item
);
2287 if ( index
!== -1 ) {
2288 if ( item
.connect
&& item
.disconnect
&& !$.isEmptyObject( this.aggregateItemEvents
) ) {
2290 for ( itemEvent
in this.aggregateItemEvents
) {
2291 events
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2293 item
.disconnect( this, events
);
2295 item
.setElementGroup( null );
2296 this.items
.splice( index
, 1 );
2297 item
.$element
.detach();
2301 this.emit( 'change', this.getItems() );
2306 * Clear all items from the group.
2308 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2309 * To remove only a subset of items from a group, use the #removeItems method.
2313 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2314 var i
, len
, item
, remove
, itemEvent
;
2317 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2318 item
= this.items
[ i
];
2320 item
.connect
&& item
.disconnect
&&
2321 !$.isEmptyObject( this.aggregateItemEvents
)
2324 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
2325 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
2327 item
.disconnect( this, remove
);
2329 item
.setElementGroup( null );
2330 item
.$element
.detach();
2333 this.emit( 'change', this.getItems() );
2339 * IconElement is often mixed into other classes to generate an icon.
2340 * Icons are graphics, about the size of normal text. They are used to aid the user
2341 * in locating a control or to convey information in a space-efficient way. See the
2342 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2343 * included in the library.
2345 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2351 * @param {Object} [config] Configuration options
2352 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2353 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2354 * the icon element be set to an existing icon instead of the one generated by this class, set a
2355 * value using a jQuery selection. For example:
2357 * // Use a <div> tag instead of a <span>
2359 * // Use an existing icon element instead of the one generated by the class
2360 * $icon: this.$element
2361 * // Use an icon element from a child widget
2362 * $icon: this.childwidget.$element
2363 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2364 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2365 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2366 * by the user's language.
2368 * Example of an i18n map:
2370 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2371 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2372 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2373 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2374 * text. The icon title is displayed when users move the mouse over the icon.
2376 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2377 // Configuration initialization
2378 config
= config
|| {};
2383 this.iconTitle
= null;
2386 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2387 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2388 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2393 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2395 /* Static Properties */
2398 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2399 * for i18n purposes and contains a `default` icon name and additional names keyed by
2400 * language code. The `default` name is used when no icon is keyed by the user's language.
2402 * Example of an i18n map:
2404 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2406 * Note: the static property will be overridden if the #icon configuration is used.
2410 * @property {Object|string}
2412 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2415 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2416 * function that returns title text, or `null` for no title.
2418 * The static property will be overridden if the #iconTitle configuration is used.
2422 * @property {string|Function|null}
2424 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2429 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2430 * applies to the specified icon element instead of the one created by the class. If an icon
2431 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2432 * and mixin methods will no longer affect the element.
2434 * @param {jQuery} $icon Element to use as icon
2436 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2439 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2440 .removeAttr( 'title' );
2444 .addClass( 'oo-ui-iconElement-icon' )
2445 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2446 if ( this.iconTitle
!== null ) {
2447 this.$icon
.attr( 'title', this.iconTitle
);
2450 this.updateThemeClasses();
2454 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2455 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2458 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2459 * by language code, or `null` to remove the icon.
2462 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2463 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2464 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2466 if ( this.icon
!== icon
) {
2468 if ( this.icon
!== null ) {
2469 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2471 if ( icon
!== null ) {
2472 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2478 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2479 this.updateThemeClasses();
2485 * Set the icon title. Use `null` to remove the title.
2487 * @param {string|Function|null} iconTitle A text string used as the icon title,
2488 * a function that returns title text, or `null` for no title.
2491 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2492 iconTitle
= typeof iconTitle
=== 'function' ||
2493 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2494 OO
.ui
.resolveMsg( iconTitle
) : null;
2496 if ( this.iconTitle
!== iconTitle
) {
2497 this.iconTitle
= iconTitle
;
2499 if ( this.iconTitle
!== null ) {
2500 this.$icon
.attr( 'title', iconTitle
);
2502 this.$icon
.removeAttr( 'title' );
2511 * Get the symbolic name of the icon.
2513 * @return {string} Icon name
2515 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2520 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2522 * @return {string} Icon title text
2524 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2525 return this.iconTitle
;
2529 * IndicatorElement is often mixed into other classes to generate an indicator.
2530 * Indicators are small graphics that are generally used in two ways:
2532 * - To draw attention to the status of an item. For example, an indicator might be
2533 * used to show that an item in a list has errors that need to be resolved.
2534 * - To clarify the function of a control that acts in an exceptional way (a button
2535 * that opens a menu instead of performing an action directly, for example).
2537 * For a list of indicators included in the library, please see the
2538 * [OOjs UI documentation on MediaWiki] [1].
2540 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2546 * @param {Object} [config] Configuration options
2547 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2548 * configuration is omitted, the indicator element will use a generated `<span>`.
2549 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2550 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2552 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2553 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2554 * or a function that returns title text. The indicator title is displayed when users move
2555 * the mouse over the indicator.
2557 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2558 // Configuration initialization
2559 config
= config
|| {};
2562 this.$indicator
= null;
2563 this.indicator
= null;
2564 this.indicatorTitle
= null;
2567 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2568 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2569 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2574 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2576 /* Static Properties */
2579 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2580 * The static property will be overridden if the #indicator configuration is used.
2584 * @property {string|null}
2586 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2589 * A text string used as the indicator title, a function that returns title text, or `null`
2590 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2594 * @property {string|Function|null}
2596 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2601 * Set the indicator element.
2603 * If an element is already set, it will be cleaned up before setting up the new element.
2605 * @param {jQuery} $indicator Element to use as indicator
2607 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2608 if ( this.$indicator
) {
2610 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2611 .removeAttr( 'title' );
2614 this.$indicator
= $indicator
2615 .addClass( 'oo-ui-indicatorElement-indicator' )
2616 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2617 if ( this.indicatorTitle
!== null ) {
2618 this.$indicator
.attr( 'title', this.indicatorTitle
);
2621 this.updateThemeClasses();
2625 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2627 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2630 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2631 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2633 if ( this.indicator
!== indicator
) {
2634 if ( this.$indicator
) {
2635 if ( this.indicator
!== null ) {
2636 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2638 if ( indicator
!== null ) {
2639 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2642 this.indicator
= indicator
;
2645 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2646 this.updateThemeClasses();
2652 * Set the indicator title.
2654 * The title is displayed when a user moves the mouse over the indicator.
2656 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2657 * `null` for no indicator title
2660 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2661 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2662 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2663 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2665 if ( this.indicatorTitle
!== indicatorTitle
) {
2666 this.indicatorTitle
= indicatorTitle
;
2667 if ( this.$indicator
) {
2668 if ( this.indicatorTitle
!== null ) {
2669 this.$indicator
.attr( 'title', indicatorTitle
);
2671 this.$indicator
.removeAttr( 'title' );
2680 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2682 * @return {string} Symbolic name of indicator
2684 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2685 return this.indicator
;
2689 * Get the indicator title.
2691 * The title is displayed when a user moves the mouse over the indicator.
2693 * @return {string} Indicator title text
2695 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2696 return this.indicatorTitle
;
2700 * LabelElement is often mixed into other classes to generate a label, which
2701 * helps identify the function of an interface element.
2702 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2704 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2710 * @param {Object} [config] Configuration options
2711 * @cfg {jQuery} [$label] The label element created by the class. If this
2712 * configuration is omitted, the label element will use a generated `<span>`.
2713 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2714 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2715 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2716 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2718 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2719 // Configuration initialization
2720 config
= config
|| {};
2727 this.setLabel( config
.label
|| this.constructor.static.label
);
2728 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2733 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2738 * @event labelChange
2739 * @param {string} value
2742 /* Static Properties */
2745 * The label text. The label can be specified as a plaintext string, a function that will
2746 * produce a string in the future, or `null` for no label. The static value will
2747 * be overridden if a label is specified with the #label config option.
2751 * @property {string|Function|null}
2753 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2755 /* Static methods */
2758 * Highlight the first occurrence of the query in the given text
2760 * @param {string} text Text
2761 * @param {string} query Query to find
2762 * @return {jQuery} Text with the first match of the query
2763 * sub-string wrapped in highlighted span
2765 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2766 var $result
= $( '<span>' ),
2767 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2769 if ( !query
.length
|| offset
=== -1 ) {
2770 return $result
.text( text
);
2773 document
.createTextNode( text
.slice( 0, offset
) ),
2775 .addClass( 'oo-ui-labelElement-label-highlight' )
2776 .text( text
.slice( offset
, offset
+ query
.length
) ),
2777 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2779 return $result
.contents();
2785 * Set the label element.
2787 * If an element is already set, it will be cleaned up before setting up the new element.
2789 * @param {jQuery} $label Element to use as label
2791 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2792 if ( this.$label
) {
2793 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2796 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2797 this.setLabelContent( this.label
);
2803 * An empty string will result in the label being hidden. A string containing only whitespace will
2804 * be converted to a single ` `.
2806 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2807 * text; or null for no label
2810 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2811 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
2812 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
2814 if ( this.label
!== label
) {
2815 if ( this.$label
) {
2816 this.setLabelContent( label
);
2819 this.emit( 'labelChange' );
2822 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
2828 * Set the label as plain text with a highlighted query
2830 * @param {string} text Text label to set
2831 * @param {string} query Substring of text to highlight
2834 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
2835 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
2841 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
2842 * text; or null for no label
2844 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
2852 * @deprecated since 0.16.0
2854 OO
.ui
.mixin
.LabelElement
.prototype.fitLabel = function () {
2859 * Set the content of the label.
2861 * Do not call this method until after the label element has been set by #setLabelElement.
2864 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2865 * text; or null for no label
2867 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
2868 if ( typeof label
=== 'string' ) {
2869 if ( label
.match( /^\s*$/ ) ) {
2870 // Convert whitespace only string to a single non-breaking space
2871 this.$label
.html( ' ' );
2873 this.$label
.text( label
);
2875 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
2876 this.$label
.html( label
.toString() );
2877 } else if ( label
instanceof jQuery
) {
2878 this.$label
.empty().append( label
);
2880 this.$label
.empty();
2885 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
2886 * additional functionality to an element created by another class. The class provides
2887 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
2888 * which are used to customize the look and feel of a widget to better describe its
2889 * importance and functionality.
2891 * The library currently contains the following styling flags for general use:
2893 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
2894 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
2895 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
2897 * The flags affect the appearance of the buttons:
2900 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
2901 * var button1 = new OO.ui.ButtonWidget( {
2902 * label: 'Constructive',
2903 * flags: 'constructive'
2905 * var button2 = new OO.ui.ButtonWidget( {
2906 * label: 'Destructive',
2907 * flags: 'destructive'
2909 * var button3 = new OO.ui.ButtonWidget( {
2910 * label: 'Progressive',
2911 * flags: 'progressive'
2913 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
2915 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
2916 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
2918 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2924 * @param {Object} [config] Configuration options
2925 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
2926 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
2927 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
2928 * @cfg {jQuery} [$flagged] The flagged element. By default,
2929 * the flagged functionality is applied to the element created by the class ($element).
2930 * If a different element is specified, the flagged functionality will be applied to it instead.
2932 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
2933 // Configuration initialization
2934 config
= config
|| {};
2938 this.$flagged
= null;
2941 this.setFlags( config
.flags
);
2942 this.setFlaggedElement( config
.$flagged
|| this.$element
);
2949 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
2950 * parameter contains the name of each modified flag and indicates whether it was
2953 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
2954 * that the flag was added, `false` that the flag was removed.
2960 * Set the flagged element.
2962 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
2963 * If an element is already set, the method will remove the mixin’s effect on that element.
2965 * @param {jQuery} $flagged Element that should be flagged
2967 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
2968 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
2969 return 'oo-ui-flaggedElement-' + flag
;
2972 if ( this.$flagged
) {
2973 this.$flagged
.removeClass( classNames
);
2976 this.$flagged
= $flagged
.addClass( classNames
);
2980 * Check if the specified flag is set.
2982 * @param {string} flag Name of flag
2983 * @return {boolean} The flag is set
2985 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
2986 // This may be called before the constructor, thus before this.flags is set
2987 return this.flags
&& ( flag
in this.flags
);
2991 * Get the names of all flags set.
2993 * @return {string[]} Flag names
2995 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
2996 // This may be called before the constructor, thus before this.flags is set
2997 return Object
.keys( this.flags
|| {} );
3006 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3007 var flag
, className
,
3010 classPrefix
= 'oo-ui-flaggedElement-';
3012 for ( flag
in this.flags
) {
3013 className
= classPrefix
+ flag
;
3014 changes
[ flag
] = false;
3015 delete this.flags
[ flag
];
3016 remove
.push( className
);
3019 if ( this.$flagged
) {
3020 this.$flagged
.removeClass( remove
.join( ' ' ) );
3023 this.updateThemeClasses();
3024 this.emit( 'flag', changes
);
3030 * Add one or more flags.
3032 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3033 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3034 * be added (`true`) or removed (`false`).
3038 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3039 var i
, len
, flag
, className
,
3043 classPrefix
= 'oo-ui-flaggedElement-';
3045 if ( typeof flags
=== 'string' ) {
3046 className
= classPrefix
+ flags
;
3048 if ( !this.flags
[ flags
] ) {
3049 this.flags
[ flags
] = true;
3050 add
.push( className
);
3052 } else if ( Array
.isArray( flags
) ) {
3053 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3055 className
= classPrefix
+ flag
;
3057 if ( !this.flags
[ flag
] ) {
3058 changes
[ flag
] = true;
3059 this.flags
[ flag
] = true;
3060 add
.push( className
);
3063 } else if ( OO
.isPlainObject( flags
) ) {
3064 for ( flag
in flags
) {
3065 className
= classPrefix
+ flag
;
3066 if ( flags
[ flag
] ) {
3068 if ( !this.flags
[ flag
] ) {
3069 changes
[ flag
] = true;
3070 this.flags
[ flag
] = true;
3071 add
.push( className
);
3075 if ( this.flags
[ flag
] ) {
3076 changes
[ flag
] = false;
3077 delete this.flags
[ flag
];
3078 remove
.push( className
);
3084 if ( this.$flagged
) {
3086 .addClass( add
.join( ' ' ) )
3087 .removeClass( remove
.join( ' ' ) );
3090 this.updateThemeClasses();
3091 this.emit( 'flag', changes
);
3097 * TitledElement is mixed into other classes to provide a `title` attribute.
3098 * Titles are rendered by the browser and are made visible when the user moves
3099 * the mouse over the element. Titles are not visible on touch devices.
3102 * // TitledElement provides a 'title' attribute to the
3103 * // ButtonWidget class
3104 * var button = new OO.ui.ButtonWidget( {
3105 * label: 'Button with Title',
3106 * title: 'I am a button'
3108 * $( 'body' ).append( button.$element );
3114 * @param {Object} [config] Configuration options
3115 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3116 * If this config is omitted, the title functionality is applied to $element, the
3117 * element created by the class.
3118 * @cfg {string|Function} [title] The title text or a function that returns text. If
3119 * this config is omitted, the value of the {@link #static-title static title} property is used.
3121 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3122 // Configuration initialization
3123 config
= config
|| {};
3126 this.$titled
= null;
3130 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3131 this.setTitledElement( config
.$titled
|| this.$element
);
3136 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3138 /* Static Properties */
3141 * The title text, a function that returns text, or `null` for no title. The value of the static property
3142 * is overridden if the #title config option is used.
3146 * @property {string|Function|null}
3148 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3153 * Set the titled element.
3155 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3156 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3158 * @param {jQuery} $titled Element that should use the 'titled' functionality
3160 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3161 if ( this.$titled
) {
3162 this.$titled
.removeAttr( 'title' );
3165 this.$titled
= $titled
;
3167 this.$titled
.attr( 'title', this.title
);
3174 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3177 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3178 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3179 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3181 if ( this.title
!== title
) {
3182 if ( this.$titled
) {
3183 if ( title
!== null ) {
3184 this.$titled
.attr( 'title', title
);
3186 this.$titled
.removeAttr( 'title' );
3198 * @return {string} Title string
3200 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3205 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3206 * Accesskeys allow an user to go to a specific element by using
3207 * a shortcut combination of a browser specific keys + the key
3211 * // AccessKeyedElement provides an 'accesskey' attribute to the
3212 * // ButtonWidget class
3213 * var button = new OO.ui.ButtonWidget( {
3214 * label: 'Button with Accesskey',
3217 * $( 'body' ).append( button.$element );
3223 * @param {Object} [config] Configuration options
3224 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3225 * If this config is omitted, the accesskey functionality is applied to $element, the
3226 * element created by the class.
3227 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3228 * this config is omitted, no accesskey will be added.
3230 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3231 // Configuration initialization
3232 config
= config
|| {};
3235 this.$accessKeyed
= null;
3236 this.accessKey
= null;
3239 this.setAccessKey( config
.accessKey
|| null );
3240 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3245 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3247 /* Static Properties */
3250 * The access key, a function that returns a key, or `null` for no accesskey.
3254 * @property {string|Function|null}
3256 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3261 * Set the accesskeyed element.
3263 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3264 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3266 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3268 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3269 if ( this.$accessKeyed
) {
3270 this.$accessKeyed
.removeAttr( 'accesskey' );
3273 this.$accessKeyed
= $accessKeyed
;
3274 if ( this.accessKey
) {
3275 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3282 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3285 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3286 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3288 if ( this.accessKey
!== accessKey
) {
3289 if ( this.$accessKeyed
) {
3290 if ( accessKey
!== null ) {
3291 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3293 this.$accessKeyed
.removeAttr( 'accesskey' );
3296 this.accessKey
= accessKey
;
3305 * @return {string} accessKey string
3307 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3308 return this.accessKey
;
3312 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3313 * feels, and functionality can be customized via the class’s configuration options
3314 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3317 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3320 * // A button widget
3321 * var button = new OO.ui.ButtonWidget( {
3322 * label: 'Button with Icon',
3324 * iconTitle: 'Remove'
3326 * $( 'body' ).append( button.$element );
3328 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3331 * @extends OO.ui.Widget
3332 * @mixins OO.ui.mixin.ButtonElement
3333 * @mixins OO.ui.mixin.IconElement
3334 * @mixins OO.ui.mixin.IndicatorElement
3335 * @mixins OO.ui.mixin.LabelElement
3336 * @mixins OO.ui.mixin.TitledElement
3337 * @mixins OO.ui.mixin.FlaggedElement
3338 * @mixins OO.ui.mixin.TabIndexedElement
3339 * @mixins OO.ui.mixin.AccessKeyedElement
3342 * @param {Object} [config] Configuration options
3343 * @cfg {boolean} [active=false] Whether button should be shown as active
3344 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3345 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3346 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3348 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3349 // Configuration initialization
3350 config
= config
|| {};
3352 // Parent constructor
3353 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3355 // Mixin constructors
3356 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3357 OO
.ui
.mixin
.IconElement
.call( this, config
);
3358 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3359 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3360 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3361 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3362 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3363 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3368 this.noFollow
= false;
3371 this.connect( this, { disable
: 'onDisable' } );
3374 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3376 .addClass( 'oo-ui-buttonWidget' )
3377 .append( this.$button
);
3378 this.setActive( config
.active
);
3379 this.setHref( config
.href
);
3380 this.setTarget( config
.target
);
3381 this.setNoFollow( config
.noFollow
);
3386 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3387 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3388 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3389 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3390 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3391 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3392 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3393 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3394 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3401 OO
.ui
.ButtonWidget
.prototype.onMouseDown = function ( e
) {
3402 if ( !this.isDisabled() ) {
3403 // Remove the tab-index while the button is down to prevent the button from stealing focus
3404 this.$button
.removeAttr( 'tabindex' );
3407 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown
.call( this, e
);
3413 OO
.ui
.ButtonWidget
.prototype.onMouseUp = function ( e
) {
3414 if ( !this.isDisabled() ) {
3415 // Restore the tab-index after the button is up to restore the button's accessibility
3416 this.$button
.attr( 'tabindex', this.tabIndex
);
3419 return OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp
.call( this, e
);
3423 * Get hyperlink location.
3425 * @return {string} Hyperlink location
3427 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3432 * Get hyperlink target.
3434 * @return {string} Hyperlink target
3436 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3441 * Get search engine traversal hint.
3443 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3445 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3446 return this.noFollow
;
3450 * Set hyperlink location.
3452 * @param {string|null} href Hyperlink location, null to remove
3454 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3455 href
= typeof href
=== 'string' ? href
: null;
3456 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3460 if ( href
!== this.href
) {
3469 * Update the `href` attribute, in case of changes to href or
3475 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3476 if ( this.href
!== null && !this.isDisabled() ) {
3477 this.$button
.attr( 'href', this.href
);
3479 this.$button
.removeAttr( 'href' );
3486 * Handle disable events.
3489 * @param {boolean} disabled Element is disabled
3491 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3496 * Set hyperlink target.
3498 * @param {string|null} target Hyperlink target, null to remove
3500 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3501 target
= typeof target
=== 'string' ? target
: null;
3503 if ( target
!== this.target
) {
3504 this.target
= target
;
3505 if ( target
!== null ) {
3506 this.$button
.attr( 'target', target
);
3508 this.$button
.removeAttr( 'target' );
3516 * Set search engine traversal hint.
3518 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3520 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3521 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3523 if ( noFollow
!== this.noFollow
) {
3524 this.noFollow
= noFollow
;
3526 this.$button
.attr( 'rel', 'nofollow' );
3528 this.$button
.removeAttr( 'rel' );
3535 // Override method visibility hints from ButtonElement
3544 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3545 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3546 * removed, and cleared from the group.
3549 * // Example: A ButtonGroupWidget with two buttons
3550 * var button1 = new OO.ui.PopupButtonWidget( {
3551 * label: 'Select a category',
3554 * $content: $( '<p>List of categories...</p>' ),
3559 * var button2 = new OO.ui.ButtonWidget( {
3562 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3563 * items: [button1, button2]
3565 * $( 'body' ).append( buttonGroup.$element );
3568 * @extends OO.ui.Widget
3569 * @mixins OO.ui.mixin.GroupElement
3572 * @param {Object} [config] Configuration options
3573 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3575 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3576 // Configuration initialization
3577 config
= config
|| {};
3579 // Parent constructor
3580 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3582 // Mixin constructors
3583 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3586 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3587 if ( Array
.isArray( config
.items
) ) {
3588 this.addItems( config
.items
);
3594 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3595 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3598 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3599 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3600 * for a list of icons included in the library.
3603 * // An icon widget with a label
3604 * var myIcon = new OO.ui.IconWidget( {
3608 * // Create a label.
3609 * var iconLabel = new OO.ui.LabelWidget( {
3612 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3614 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3617 * @extends OO.ui.Widget
3618 * @mixins OO.ui.mixin.IconElement
3619 * @mixins OO.ui.mixin.TitledElement
3620 * @mixins OO.ui.mixin.FlaggedElement
3623 * @param {Object} [config] Configuration options
3625 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3626 // Configuration initialization
3627 config
= config
|| {};
3629 // Parent constructor
3630 OO
.ui
.IconWidget
.parent
.call( this, config
);
3632 // Mixin constructors
3633 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3634 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3635 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3638 this.$element
.addClass( 'oo-ui-iconWidget' );
3643 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3644 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3645 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3646 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3648 /* Static Properties */
3650 OO
.ui
.IconWidget
.static.tagName
= 'span';
3653 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3654 * attention to the status of an item or to clarify the function of a control. For a list of
3655 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3658 * // Example of an indicator widget
3659 * var indicator1 = new OO.ui.IndicatorWidget( {
3660 * indicator: 'alert'
3663 * // Create a fieldset layout to add a label
3664 * var fieldset = new OO.ui.FieldsetLayout();
3665 * fieldset.addItems( [
3666 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3668 * $( 'body' ).append( fieldset.$element );
3670 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3673 * @extends OO.ui.Widget
3674 * @mixins OO.ui.mixin.IndicatorElement
3675 * @mixins OO.ui.mixin.TitledElement
3678 * @param {Object} [config] Configuration options
3680 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3681 // Configuration initialization
3682 config
= config
|| {};
3684 // Parent constructor
3685 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3687 // Mixin constructors
3688 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3689 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3692 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3697 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3698 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3699 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3701 /* Static Properties */
3703 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3706 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3707 * be configured with a `label` option that is set to a string, a label node, or a function:
3709 * - String: a plaintext string
3710 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3711 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3712 * - Function: a function that will produce a string in the future. Functions are used
3713 * in cases where the value of the label is not currently defined.
3715 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3716 * will come into focus when the label is clicked.
3719 * // Examples of LabelWidgets
3720 * var label1 = new OO.ui.LabelWidget( {
3721 * label: 'plaintext label'
3723 * var label2 = new OO.ui.LabelWidget( {
3724 * label: $( '<a href="default.html">jQuery label</a>' )
3726 * // Create a fieldset layout with fields for each example
3727 * var fieldset = new OO.ui.FieldsetLayout();
3728 * fieldset.addItems( [
3729 * new OO.ui.FieldLayout( label1 ),
3730 * new OO.ui.FieldLayout( label2 )
3732 * $( 'body' ).append( fieldset.$element );
3735 * @extends OO.ui.Widget
3736 * @mixins OO.ui.mixin.LabelElement
3737 * @mixins OO.ui.mixin.TitledElement
3740 * @param {Object} [config] Configuration options
3741 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3742 * Clicking the label will focus the specified input field.
3744 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3745 // Configuration initialization
3746 config
= config
|| {};
3748 // Parent constructor
3749 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3751 // Mixin constructors
3752 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3753 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3756 this.input
= config
.input
;
3759 if ( this.input
instanceof OO
.ui
.InputWidget
) {
3760 this.$element
.on( 'click', this.onClick
.bind( this ) );
3764 this.$element
.addClass( 'oo-ui-labelWidget' );
3769 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3770 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3771 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3773 /* Static Properties */
3775 OO
.ui
.LabelWidget
.static.tagName
= 'span';
3780 * Handles label mouse click events.
3783 * @param {jQuery.Event} e Mouse click event
3785 OO
.ui
.LabelWidget
.prototype.onClick = function () {
3786 this.input
.simulateLabelClick();
3791 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3792 * and that they should wait before proceeding. The pending state is visually represented with a pending
3793 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3794 * field of a {@link OO.ui.TextInputWidget text input widget}.
3796 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
3797 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
3798 * in process dialogs.
3801 * function MessageDialog( config ) {
3802 * MessageDialog.parent.call( this, config );
3804 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
3806 * MessageDialog.static.actions = [
3807 * { action: 'save', label: 'Done', flags: 'primary' },
3808 * { label: 'Cancel', flags: 'safe' }
3811 * MessageDialog.prototype.initialize = function () {
3812 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
3813 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
3814 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
3815 * this.$body.append( this.content.$element );
3817 * MessageDialog.prototype.getBodyHeight = function () {
3820 * MessageDialog.prototype.getActionProcess = function ( action ) {
3821 * var dialog = this;
3822 * if ( action === 'save' ) {
3823 * dialog.getActions().get({actions: 'save'})[0].pushPending();
3824 * return new OO.ui.Process()
3826 * .next( function () {
3827 * dialog.getActions().get({actions: 'save'})[0].popPending();
3830 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
3833 * var windowManager = new OO.ui.WindowManager();
3834 * $( 'body' ).append( windowManager.$element );
3836 * var dialog = new MessageDialog();
3837 * windowManager.addWindows( [ dialog ] );
3838 * windowManager.openWindow( dialog );
3844 * @param {Object} [config] Configuration options
3845 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
3847 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
3848 // Configuration initialization
3849 config
= config
|| {};
3853 this.$pending
= null;
3856 this.setPendingElement( config
.$pending
|| this.$element
);
3861 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
3866 * Set the pending element (and clean up any existing one).
3868 * @param {jQuery} $pending The element to set to pending.
3870 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
3871 if ( this.$pending
) {
3872 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3875 this.$pending
= $pending
;
3876 if ( this.pending
> 0 ) {
3877 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3882 * Check if an element is pending.
3884 * @return {boolean} Element is pending
3886 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
3887 return !!this.pending
;
3891 * Increase the pending counter. The pending state will remain active until the counter is zero
3892 * (i.e., the number of calls to #pushPending and #popPending is the same).
3896 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
3897 if ( this.pending
=== 0 ) {
3898 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
3899 this.updateThemeClasses();
3907 * Decrease the pending counter. The pending state will remain active until the counter is zero
3908 * (i.e., the number of calls to #pushPending and #popPending is the same).
3912 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
3913 if ( this.pending
=== 1 ) {
3914 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
3915 this.updateThemeClasses();
3917 this.pending
= Math
.max( 0, this.pending
- 1 );
3923 * Element that can be automatically clipped to visible boundaries.
3925 * Whenever the element's natural height changes, you have to call
3926 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
3927 * clipping correctly.
3929 * The dimensions of #$clippableContainer will be compared to the boundaries of the
3930 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
3931 * then #$clippable will be given a fixed reduced height and/or width and will be made
3932 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
3933 * but you can build a static footer by setting #$clippableContainer to an element that contains
3934 * #$clippable and the footer.
3940 * @param {Object} [config] Configuration options
3941 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
3942 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
3943 * omit to use #$clippable
3945 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
3946 // Configuration initialization
3947 config
= config
|| {};
3950 this.$clippable
= null;
3951 this.$clippableContainer
= null;
3952 this.clipping
= false;
3953 this.clippedHorizontally
= false;
3954 this.clippedVertically
= false;
3955 this.$clippableScrollableContainer
= null;
3956 this.$clippableScroller
= null;
3957 this.$clippableWindow
= null;
3958 this.idealWidth
= null;
3959 this.idealHeight
= null;
3960 this.onClippableScrollHandler
= this.clip
.bind( this );
3961 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
3964 if ( config
.$clippableContainer
) {
3965 this.setClippableContainer( config
.$clippableContainer
);
3967 this.setClippableElement( config
.$clippable
|| this.$element
);
3973 * Set clippable element.
3975 * If an element is already set, it will be cleaned up before setting up the new element.
3977 * @param {jQuery} $clippable Element to make clippable
3979 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
3980 if ( this.$clippable
) {
3981 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
3982 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
3983 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
3986 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
3991 * Set clippable container.
3993 * This is the container that will be measured when deciding whether to clip. When clipping,
3994 * #$clippable will be resized in order to keep the clippable container fully visible.
3996 * If the clippable container is unset, #$clippable will be used.
3998 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4000 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4001 this.$clippableContainer
= $clippableContainer
;
4002 if ( this.$clippable
) {
4010 * Do not turn clipping on until after the element is attached to the DOM and visible.
4012 * @param {boolean} [clipping] Enable clipping, omit to toggle
4015 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4016 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4018 if ( this.clipping
!== clipping
) {
4019 this.clipping
= clipping
;
4021 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4022 // If the clippable container is the root, we have to listen to scroll events and check
4023 // jQuery.scrollTop on the window because of browser inconsistencies
4024 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4025 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4026 this.$clippableScrollableContainer
;
4027 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4028 this.$clippableWindow
= $( this.getElementWindow() )
4029 .on( 'resize', this.onClippableWindowResizeHandler
);
4030 // Initial clip after visible
4033 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4034 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4036 this.$clippableScrollableContainer
= null;
4037 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4038 this.$clippableScroller
= null;
4039 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4040 this.$clippableWindow
= null;
4048 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4050 * @return {boolean} Element will be clipped to the visible area
4052 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4053 return this.clipping
;
4057 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4059 * @return {boolean} Part of the element is being clipped
4061 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4062 return this.clippedHorizontally
|| this.clippedVertically
;
4066 * Check if the right of the element is being clipped by the nearest scrollable container.
4068 * @return {boolean} Part of the element is being clipped
4070 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4071 return this.clippedHorizontally
;
4075 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4077 * @return {boolean} Part of the element is being clipped
4079 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4080 return this.clippedVertically
;
4084 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
4086 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4087 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4089 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4090 this.idealWidth
= width
;
4091 this.idealHeight
= height
;
4093 if ( !this.clipping
) {
4094 // Update dimensions
4095 this.$clippable
.css( { width
: width
, height
: height
} );
4097 // While clipping, idealWidth and idealHeight are not considered
4101 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4102 * when the element's natural height changes.
4104 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4105 * overlapped by, the visible area of the nearest scrollable container.
4107 * Because calling clip() when the natural height changes isn't always possible, we also set
4108 * max-height when the element isn't being clipped. This means that if the element tries to grow
4109 * beyond the edge, something reasonable will happen before clip() is called.
4113 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4114 var $container
, extraHeight
, extraWidth
, ccOffset
,
4115 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4116 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4117 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4118 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4119 buffer
= 7; // Chosen by fair dice roll
4121 if ( !this.clipping
) {
4122 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4126 $container
= this.$clippableContainer
|| this.$clippable
;
4127 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4128 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4129 ccOffset
= $container
.offset();
4130 $scrollableContainer
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4131 this.$clippableWindow
: this.$clippableScrollableContainer
;
4132 scOffset
= $scrollableContainer
.offset() || { top
: 0, left
: 0 };
4133 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4134 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4135 ccWidth
= $container
.outerWidth() + buffer
;
4136 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4137 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4138 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4139 desiredWidth
= ccOffset
.left
< 0 ?
4140 ccWidth
+ ccOffset
.left
:
4141 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4142 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4143 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4144 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4145 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4146 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4147 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4148 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4149 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4150 clipWidth
= allotedWidth
< naturalWidth
;
4151 clipHeight
= allotedHeight
< naturalHeight
;
4154 this.$clippable
.css( {
4155 overflowX
: 'scroll',
4156 width
: Math
.max( 0, allotedWidth
),
4160 this.$clippable
.css( {
4162 width
: this.idealWidth
? this.idealWidth
- extraWidth
: '',
4163 maxWidth
: Math
.max( 0, allotedWidth
)
4167 this.$clippable
.css( {
4168 overflowY
: 'scroll',
4169 height
: Math
.max( 0, allotedHeight
),
4173 this.$clippable
.css( {
4175 height
: this.idealHeight
? this.idealHeight
- extraHeight
: '',
4176 maxHeight
: Math
.max( 0, allotedHeight
)
4180 // If we stopped clipping in at least one of the dimensions
4181 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4182 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4185 this.clippedHorizontally
= clipWidth
;
4186 this.clippedVertically
= clipHeight
;
4192 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4193 * By default, each popup has an anchor that points toward its origin.
4194 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4197 * // A popup widget.
4198 * var popup = new OO.ui.PopupWidget( {
4199 * $content: $( '<p>Hi there!</p>' ),
4204 * $( 'body' ).append( popup.$element );
4205 * // To display the popup, toggle the visibility to 'true'.
4206 * popup.toggle( true );
4208 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4211 * @extends OO.ui.Widget
4212 * @mixins OO.ui.mixin.LabelElement
4213 * @mixins OO.ui.mixin.ClippableElement
4216 * @param {Object} [config] Configuration options
4217 * @cfg {number} [width=320] Width of popup in pixels
4218 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4219 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4220 * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`.
4221 * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the
4222 * popup is leaning towards the right of the screen.
4223 * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence
4224 * in the given language, which means it will flip to the correct positioning in right-to-left languages.
4225 * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the
4226 * sentence in the given language.
4227 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4228 * See the [OOjs UI docs on MediaWiki][3] for an example.
4229 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4230 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4231 * @cfg {jQuery} [$content] Content to append to the popup's body
4232 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4233 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4234 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4235 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4237 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4238 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4240 * @cfg {boolean} [padded=false] Add padding to the popup's body
4242 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4243 // Configuration initialization
4244 config
= config
|| {};
4246 // Parent constructor
4247 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4249 // Properties (must be set before ClippableElement constructor call)
4250 this.$body
= $( '<div>' );
4251 this.$popup
= $( '<div>' );
4253 // Mixin constructors
4254 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4255 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4256 $clippable
: this.$body
,
4257 $clippableContainer
: this.$popup
4261 this.$anchor
= $( '<div>' );
4262 // If undefined, will be computed lazily in updateDimensions()
4263 this.$container
= config
.$container
;
4264 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4265 this.autoClose
= !!config
.autoClose
;
4266 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4267 this.transitionTimeout
= null;
4269 this.width
= config
.width
!== undefined ? config
.width
: 320;
4270 this.height
= config
.height
!== undefined ? config
.height
: null;
4271 this.setAlignment( config
.align
);
4272 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4273 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4276 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4277 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4278 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4280 .addClass( 'oo-ui-popupWidget-popup' )
4281 .append( this.$body
);
4283 .addClass( 'oo-ui-popupWidget' )
4284 .append( this.$popup
, this.$anchor
);
4285 // Move content, which was added to #$element by OO.ui.Widget, to the body
4286 // FIXME This is gross, we should use '$body' or something for the config
4287 if ( config
.$content
instanceof jQuery
) {
4288 this.$body
.append( config
.$content
);
4291 if ( config
.padded
) {
4292 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4295 if ( config
.head
) {
4296 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4297 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4298 this.$head
= $( '<div>' )
4299 .addClass( 'oo-ui-popupWidget-head' )
4300 .append( this.$label
, this.closeButton
.$element
);
4301 this.$popup
.prepend( this.$head
);
4304 if ( config
.$footer
) {
4305 this.$footer
= $( '<div>' )
4306 .addClass( 'oo-ui-popupWidget-footer' )
4307 .append( config
.$footer
);
4308 this.$popup
.append( this.$footer
);
4311 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4312 // that reference properties not initialized at that time of parent class construction
4313 // TODO: Find a better way to handle post-constructor setup
4314 this.visible
= false;
4315 this.$element
.addClass( 'oo-ui-element-hidden' );
4320 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4321 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4322 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4327 * Handles mouse down events.
4330 * @param {MouseEvent} e Mouse down event
4332 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4335 !$.contains( this.$element
[ 0 ], e
.target
) &&
4336 ( !this.$autoCloseIgnore
|| !this.$autoCloseIgnore
.has( e
.target
).length
)
4338 this.toggle( false );
4343 * Bind mouse down listener.
4347 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
4348 // Capture clicks outside popup
4349 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
4353 * Handles close button click events.
4357 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
4358 if ( this.isVisible() ) {
4359 this.toggle( false );
4364 * Unbind mouse down listener.
4368 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
4369 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
4373 * Handles key down events.
4376 * @param {KeyboardEvent} e Key down event
4378 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
4380 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
4383 this.toggle( false );
4385 e
.stopPropagation();
4390 * Bind key down listener.
4394 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
4395 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4399 * Unbind key down listener.
4403 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
4404 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
4408 * Show, hide, or toggle the visibility of the anchor.
4410 * @param {boolean} [show] Show anchor, omit to toggle
4412 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
4413 show
= show
=== undefined ? !this.anchored
: !!show
;
4415 if ( this.anchored
!== show
) {
4417 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
4419 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
4421 this.anchored
= show
;
4426 * Check if the anchor is visible.
4428 * @return {boolean} Anchor is visible
4430 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
4437 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
4439 show
= show
=== undefined ? !this.isVisible() : !!show
;
4441 change
= show
!== this.isVisible();
4444 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
4448 if ( this.autoClose
) {
4449 this.bindMouseDownListener();
4450 this.bindKeyDownListener();
4452 this.updateDimensions();
4453 this.toggleClipping( true );
4455 this.toggleClipping( false );
4456 if ( this.autoClose
) {
4457 this.unbindMouseDownListener();
4458 this.unbindKeyDownListener();
4467 * Set the size of the popup.
4469 * Changing the size may also change the popup's position depending on the alignment.
4471 * @param {number} width Width in pixels
4472 * @param {number} height Height in pixels
4473 * @param {boolean} [transition=false] Use a smooth transition
4476 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
4478 this.height
= height
!== undefined ? height
: null;
4479 if ( this.isVisible() ) {
4480 this.updateDimensions( transition
);
4485 * Update the size and position.
4487 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
4488 * be called automatically.
4490 * @param {boolean} [transition=false] Use a smooth transition
4493 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
4494 var popupOffset
, originOffset
, containerLeft
, containerWidth
, containerRight
,
4495 popupLeft
, popupRight
, overlapLeft
, overlapRight
, anchorWidth
,
4499 if ( !this.$container
) {
4500 // Lazy-initialize $container if not specified in constructor
4501 this.$container
= $( this.getClosestScrollableElementContainer() );
4504 // Set height and width before measuring things, since it might cause our measurements
4505 // to change (e.g. due to scrollbars appearing or disappearing)
4508 height
: this.height
!== null ? this.height
: 'auto'
4511 // If we are in RTL, we need to flip the alignment, unless it is center
4512 if ( align
=== 'forwards' || align
=== 'backwards' ) {
4513 if ( this.$container
.css( 'direction' ) === 'rtl' ) {
4514 align
= ( { forwards
: 'force-left', backwards
: 'force-right' } )[ this.align
];
4516 align
= ( { forwards
: 'force-right', backwards
: 'force-left' } )[ this.align
];
4521 // Compute initial popupOffset based on alignment
4522 popupOffset
= this.width
* ( { 'force-left': -1, center
: -0.5, 'force-right': 0 } )[ align
];
4524 // Figure out if this will cause the popup to go beyond the edge of the container
4525 originOffset
= this.$element
.offset().left
;
4526 containerLeft
= this.$container
.offset().left
;
4527 containerWidth
= this.$container
.innerWidth();
4528 containerRight
= containerLeft
+ containerWidth
;
4529 popupLeft
= popupOffset
- this.containerPadding
;
4530 popupRight
= popupOffset
+ this.containerPadding
+ this.width
+ this.containerPadding
;
4531 overlapLeft
= ( originOffset
+ popupLeft
) - containerLeft
;
4532 overlapRight
= containerRight
- ( originOffset
+ popupRight
);
4534 // Adjust offset to make the popup not go beyond the edge, if needed
4535 if ( overlapRight
< 0 ) {
4536 popupOffset
+= overlapRight
;
4537 } else if ( overlapLeft
< 0 ) {
4538 popupOffset
-= overlapLeft
;
4541 // Adjust offset to avoid anchor being rendered too close to the edge
4542 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
4543 // TODO: Find a measurement that works for CSS anchors and image anchors
4544 anchorWidth
= this.$anchor
[ 0 ].scrollWidth
* 2;
4545 if ( popupOffset
+ this.width
< anchorWidth
) {
4546 popupOffset
= anchorWidth
- this.width
;
4547 } else if ( -popupOffset
< anchorWidth
) {
4548 popupOffset
= -anchorWidth
;
4551 // Prevent transition from being interrupted
4552 clearTimeout( this.transitionTimeout
);
4554 // Enable transition
4555 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
4558 // Position body relative to anchor
4559 this.$popup
.css( 'margin-left', popupOffset
);
4562 // Prevent transitioning after transition is complete
4563 this.transitionTimeout
= setTimeout( function () {
4564 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4567 // Prevent transitioning immediately
4568 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
4571 // Reevaluate clipping state since we've relocated and resized the popup
4578 * Set popup alignment
4580 * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4581 * `backwards` or `forwards`.
4583 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
4584 // Validate alignment and transform deprecated values
4585 if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
4586 this.align
= { left
: 'force-right', right
: 'force-left' }[ align
] || align
;
4588 this.align
= 'center';
4593 * Get popup alignment
4595 * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`,
4596 * `backwards` or `forwards`.
4598 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
4603 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
4604 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
4605 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
4606 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
4612 * @param {Object} [config] Configuration options
4613 * @cfg {Object} [popup] Configuration to pass to popup
4614 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
4616 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
4617 // Configuration initialization
4618 config
= config
|| {};
4621 this.popup
= new OO
.ui
.PopupWidget( $.extend(
4622 { autoClose
: true },
4624 { $autoCloseIgnore
: this.$element
}
4633 * @return {OO.ui.PopupWidget} Popup widget
4635 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
4640 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
4641 * which is used to display additional information or options.
4644 * // Example of a popup button.
4645 * var popupButton = new OO.ui.PopupButtonWidget( {
4646 * label: 'Popup button with options',
4649 * $content: $( '<p>Additional options here.</p>' ),
4651 * align: 'force-left'
4654 * // Append the button to the DOM.
4655 * $( 'body' ).append( popupButton.$element );
4658 * @extends OO.ui.ButtonWidget
4659 * @mixins OO.ui.mixin.PopupElement
4662 * @param {Object} [config] Configuration options
4664 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
4665 // Parent constructor
4666 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
4668 // Mixin constructors
4669 OO
.ui
.mixin
.PopupElement
.call( this, config
);
4672 this.connect( this, { click
: 'onAction' } );
4676 .addClass( 'oo-ui-popupButtonWidget' )
4677 .attr( 'aria-haspopup', 'true' )
4678 .append( this.popup
.$element
);
4683 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
4684 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
4689 * Handle the button action being triggered.
4693 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
4694 this.popup
.toggle();
4698 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
4700 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
4705 * @mixins OO.ui.mixin.GroupElement
4708 * @param {Object} [config] Configuration options
4710 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
4711 // Mixin constructors
4712 OO
.ui
.mixin
.GroupElement
.call( this, config
);
4717 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
4722 * Set the disabled state of the widget.
4724 * This will also update the disabled state of child widgets.
4726 * @param {boolean} disabled Disable widget
4729 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
4733 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
4734 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
4736 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
4738 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
4739 this.items
[ i
].updateDisabled();
4747 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
4749 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
4750 * allows bidirectional communication.
4752 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
4760 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
4767 * Check if widget is disabled.
4769 * Checks parent if present, making disabled state inheritable.
4771 * @return {boolean} Widget is disabled
4773 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
4774 return this.disabled
||
4775 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
4779 * Set group element is in.
4781 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
4784 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
4786 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
4787 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
4789 // Initialize item disabled states
4790 this.updateDisabled();
4796 * OptionWidgets are special elements that can be selected and configured with data. The
4797 * data is often unique for each option, but it does not have to be. OptionWidgets are used
4798 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
4799 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
4801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
4804 * @extends OO.ui.Widget
4805 * @mixins OO.ui.mixin.ItemWidget
4806 * @mixins OO.ui.mixin.LabelElement
4807 * @mixins OO.ui.mixin.FlaggedElement
4808 * @mixins OO.ui.mixin.AccessKeyedElement
4811 * @param {Object} [config] Configuration options
4813 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
4814 // Configuration initialization
4815 config
= config
|| {};
4817 // Parent constructor
4818 OO
.ui
.OptionWidget
.parent
.call( this, config
);
4820 // Mixin constructors
4821 OO
.ui
.mixin
.ItemWidget
.call( this );
4822 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4823 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
4824 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
4827 this.selected
= false;
4828 this.highlighted
= false;
4829 this.pressed
= false;
4833 .data( 'oo-ui-optionWidget', this )
4834 // Allow programmatic focussing (and by accesskey), but not tabbing
4835 .attr( 'tabindex', '-1' )
4836 .attr( 'role', 'option' )
4837 .attr( 'aria-selected', 'false' )
4838 .addClass( 'oo-ui-optionWidget' )
4839 .append( this.$label
);
4844 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
4845 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
4846 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
4847 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
4848 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
4850 /* Static Properties */
4852 OO
.ui
.OptionWidget
.static.selectable
= true;
4854 OO
.ui
.OptionWidget
.static.highlightable
= true;
4856 OO
.ui
.OptionWidget
.static.pressable
= true;
4858 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
4863 * Check if the option can be selected.
4865 * @return {boolean} Item is selectable
4867 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
4868 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
4872 * Check if the option can be highlighted. A highlight indicates that the option
4873 * may be selected when a user presses enter or clicks. Disabled items cannot
4876 * @return {boolean} Item is highlightable
4878 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
4879 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
4883 * Check if the option can be pressed. The pressed state occurs when a user mouses
4884 * down on an item, but has not yet let go of the mouse.
4886 * @return {boolean} Item is pressable
4888 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
4889 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
4893 * Check if the option is selected.
4895 * @return {boolean} Item is selected
4897 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
4898 return this.selected
;
4902 * Check if the option is highlighted. A highlight indicates that the
4903 * item may be selected when a user presses enter or clicks.
4905 * @return {boolean} Item is highlighted
4907 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
4908 return this.highlighted
;
4912 * Check if the option is pressed. The pressed state occurs when a user mouses
4913 * down on an item, but has not yet let go of the mouse. The item may appear
4914 * selected, but it will not be selected until the user releases the mouse.
4916 * @return {boolean} Item is pressed
4918 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
4919 return this.pressed
;
4923 * Set the option’s selected state. In general, all modifications to the selection
4924 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
4925 * method instead of this method.
4927 * @param {boolean} [state=false] Select option
4930 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
4931 if ( this.constructor.static.selectable
) {
4932 this.selected
= !!state
;
4934 .toggleClass( 'oo-ui-optionWidget-selected', state
)
4935 .attr( 'aria-selected', state
.toString() );
4936 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
4937 this.scrollElementIntoView();
4939 this.updateThemeClasses();
4945 * Set the option’s highlighted state. In general, all programmatic
4946 * modifications to the highlight should be handled by the
4947 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
4948 * method instead of this method.
4950 * @param {boolean} [state=false] Highlight option
4953 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
4954 if ( this.constructor.static.highlightable
) {
4955 this.highlighted
= !!state
;
4956 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
4957 this.updateThemeClasses();
4963 * Set the option’s pressed state. In general, all
4964 * programmatic modifications to the pressed state should be handled by the
4965 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
4966 * method instead of this method.
4968 * @param {boolean} [state=false] Press option
4971 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
4972 if ( this.constructor.static.pressable
) {
4973 this.pressed
= !!state
;
4974 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
4975 this.updateThemeClasses();
4981 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
4982 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
4983 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
4986 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
4987 * information, please see the [OOjs UI documentation on MediaWiki][1].
4990 * // Example of a select widget with three options
4991 * var select = new OO.ui.SelectWidget( {
4993 * new OO.ui.OptionWidget( {
4995 * label: 'Option One',
4997 * new OO.ui.OptionWidget( {
4999 * label: 'Option Two',
5001 * new OO.ui.OptionWidget( {
5003 * label: 'Option Three',
5007 * $( 'body' ).append( select.$element );
5009 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5013 * @extends OO.ui.Widget
5014 * @mixins OO.ui.mixin.GroupWidget
5017 * @param {Object} [config] Configuration options
5018 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5019 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5020 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5021 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5023 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5024 // Configuration initialization
5025 config
= config
|| {};
5027 // Parent constructor
5028 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5030 // Mixin constructors
5031 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5034 this.pressed
= false;
5035 this.selecting
= null;
5036 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5037 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5038 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5039 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5040 this.keyPressBuffer
= '';
5041 this.keyPressBufferTimer
= null;
5042 this.blockMouseOverEvents
= 0;
5045 this.connect( this, {
5049 focusin
: this.onFocus
.bind( this ),
5050 mousedown
: this.onMouseDown
.bind( this ),
5051 mouseover
: this.onMouseOver
.bind( this ),
5052 mouseleave
: this.onMouseLeave
.bind( this )
5057 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5058 .attr( 'role', 'listbox' );
5059 if ( Array
.isArray( config
.items
) ) {
5060 this.addItems( config
.items
);
5066 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5067 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5074 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5076 * @param {OO.ui.OptionWidget|null} item Highlighted item
5082 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5083 * pressed state of an option.
5085 * @param {OO.ui.OptionWidget|null} item Pressed item
5091 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5093 * @param {OO.ui.OptionWidget|null} item Selected item
5098 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5099 * @param {OO.ui.OptionWidget} item Chosen item
5105 * An `add` event is emitted when options are added to the select with the #addItems method.
5107 * @param {OO.ui.OptionWidget[]} items Added items
5108 * @param {number} index Index of insertion point
5114 * A `remove` event is emitted when options are removed from the select with the #clearItems
5115 * or #removeItems methods.
5117 * @param {OO.ui.OptionWidget[]} items Removed items
5123 * Handle focus events
5126 * @param {jQuery.Event} event
5128 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5130 if ( event
.target
=== this.$element
[ 0 ] ) {
5131 // This widget was focussed, e.g. by the user tabbing to it.
5132 // The styles for focus state depend on one of the items being selected.
5133 if ( !this.getSelectedItem() ) {
5134 item
= this.getFirstSelectableItem();
5137 // One of the options got focussed (and the event bubbled up here).
5138 // They can't be tabbed to, but they can be activated using accesskeys.
5139 item
= this.getTargetItem( event
);
5143 if ( item
.constructor.static.highlightable
) {
5144 this.highlightItem( item
);
5146 this.selectItem( item
);
5150 if ( event
.target
!== this.$element
[ 0 ] ) {
5151 this.$element
.focus();
5156 * Handle mouse down events.
5159 * @param {jQuery.Event} e Mouse down event
5161 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
5164 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
5165 this.togglePressed( true );
5166 item
= this.getTargetItem( e
);
5167 if ( item
&& item
.isSelectable() ) {
5168 this.pressItem( item
);
5169 this.selecting
= item
;
5170 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
5171 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5178 * Handle mouse up events.
5181 * @param {MouseEvent} e Mouse up event
5183 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
5186 this.togglePressed( false );
5187 if ( !this.selecting
) {
5188 item
= this.getTargetItem( e
);
5189 if ( item
&& item
.isSelectable() ) {
5190 this.selecting
= item
;
5193 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
5194 this.pressItem( null );
5195 this.chooseItem( this.selecting
);
5196 this.selecting
= null;
5199 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
5200 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
5206 * Handle mouse move events.
5209 * @param {MouseEvent} e Mouse move event
5211 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
5214 if ( !this.isDisabled() && this.pressed
) {
5215 item
= this.getTargetItem( e
);
5216 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
5217 this.pressItem( item
);
5218 this.selecting
= item
;
5224 * Handle mouse over events.
5227 * @param {jQuery.Event} e Mouse over event
5229 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
5231 if ( this.blockMouseOverEvents
) {
5234 if ( !this.isDisabled() ) {
5235 item
= this.getTargetItem( e
);
5236 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
5242 * Handle mouse leave events.
5245 * @param {jQuery.Event} e Mouse over event
5247 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
5248 if ( !this.isDisabled() ) {
5249 this.highlightItem( null );
5255 * Handle key down events.
5258 * @param {KeyboardEvent} e Key down event
5260 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
5263 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
5265 if ( !this.isDisabled() && this.isVisible() ) {
5266 switch ( e
.keyCode
) {
5267 case OO
.ui
.Keys
.ENTER
:
5268 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5269 // Was only highlighted, now let's select it. No-op if already selected.
5270 this.chooseItem( currentItem
);
5275 case OO
.ui
.Keys
.LEFT
:
5276 this.clearKeyPressBuffer();
5277 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
5280 case OO
.ui
.Keys
.DOWN
:
5281 case OO
.ui
.Keys
.RIGHT
:
5282 this.clearKeyPressBuffer();
5283 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
5286 case OO
.ui
.Keys
.ESCAPE
:
5287 case OO
.ui
.Keys
.TAB
:
5288 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
5289 currentItem
.setHighlighted( false );
5291 this.unbindKeyDownListener();
5292 this.unbindKeyPressListener();
5293 // Don't prevent tabbing away / defocusing
5299 if ( nextItem
.constructor.static.highlightable
) {
5300 this.highlightItem( nextItem
);
5302 this.chooseItem( nextItem
);
5304 this.scrollItemIntoView( nextItem
);
5309 e
.stopPropagation();
5315 * Bind key down listener.
5319 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
5320 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
5324 * Unbind key down listener.
5328 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
5329 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
5333 * Scroll item into view, preventing spurious mouse highlight actions from happening.
5335 * @param {OO.ui.OptionWidget} item Item to scroll into view
5337 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
5339 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
5340 // and around 100-150 ms after it is finished.
5341 this.blockMouseOverEvents
++;
5342 item
.scrollElementIntoView().done( function () {
5343 setTimeout( function () {
5344 widget
.blockMouseOverEvents
--;
5350 * Clear the key-press buffer
5354 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
5355 if ( this.keyPressBufferTimer
) {
5356 clearTimeout( this.keyPressBufferTimer
);
5357 this.keyPressBufferTimer
= null;
5359 this.keyPressBuffer
= '';
5363 * Handle key press events.
5366 * @param {KeyboardEvent} e Key press event
5368 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
5369 var c
, filter
, item
;
5371 if ( !e
.charCode
) {
5372 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
5373 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
5378 if ( String
.fromCodePoint
) {
5379 c
= String
.fromCodePoint( e
.charCode
);
5381 c
= String
.fromCharCode( e
.charCode
);
5384 if ( this.keyPressBufferTimer
) {
5385 clearTimeout( this.keyPressBufferTimer
);
5387 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
5389 item
= this.getHighlightedItem() || this.getSelectedItem();
5391 if ( this.keyPressBuffer
=== c
) {
5392 // Common (if weird) special case: typing "xxxx" will cycle through all
5393 // the items beginning with "x".
5395 item
= this.getRelativeSelectableItem( item
, 1 );
5398 this.keyPressBuffer
+= c
;
5401 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
5402 if ( !item
|| !filter( item
) ) {
5403 item
= this.getRelativeSelectableItem( item
, 1, filter
);
5406 if ( this.isVisible() && item
.constructor.static.highlightable
) {
5407 this.highlightItem( item
);
5409 this.chooseItem( item
);
5411 this.scrollItemIntoView( item
);
5415 e
.stopPropagation();
5419 * Get a matcher for the specific string
5422 * @param {string} s String to match against items
5423 * @param {boolean} [exact=false] Only accept exact matches
5424 * @return {Function} function ( OO.ui.OptionItem ) => boolean
5426 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
5429 if ( s
.normalize
) {
5432 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
5433 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
5437 re
= new RegExp( re
, 'i' );
5438 return function ( item
) {
5439 var l
= item
.getLabel();
5440 if ( typeof l
!== 'string' ) {
5441 l
= item
.$label
.text();
5443 if ( l
.normalize
) {
5446 return re
.test( l
);
5451 * Bind key press listener.
5455 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
5456 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
5460 * Unbind key down listener.
5462 * If you override this, be sure to call this.clearKeyPressBuffer() from your
5467 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
5468 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
5469 this.clearKeyPressBuffer();
5473 * Visibility change handler
5476 * @param {boolean} visible
5478 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
5480 this.clearKeyPressBuffer();
5485 * Get the closest item to a jQuery.Event.
5488 * @param {jQuery.Event} e
5489 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
5491 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
5492 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
5496 * Get selected item.
5498 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
5500 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
5503 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5504 if ( this.items
[ i
].isSelected() ) {
5505 return this.items
[ i
];
5512 * Get highlighted item.
5514 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
5516 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
5519 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5520 if ( this.items
[ i
].isHighlighted() ) {
5521 return this.items
[ i
];
5528 * Toggle pressed state.
5530 * Press is a state that occurs when a user mouses down on an item, but
5531 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
5532 * until the user releases the mouse.
5534 * @param {boolean} pressed An option is being pressed
5536 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
5537 if ( pressed
=== undefined ) {
5538 pressed
= !this.pressed
;
5540 if ( pressed
!== this.pressed
) {
5542 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
5543 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
5544 this.pressed
= pressed
;
5549 * Highlight an option. If the `item` param is omitted, no options will be highlighted
5550 * and any existing highlight will be removed. The highlight is mutually exclusive.
5552 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
5556 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
5557 var i
, len
, highlighted
,
5560 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5561 highlighted
= this.items
[ i
] === item
;
5562 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
5563 this.items
[ i
].setHighlighted( highlighted
);
5568 this.emit( 'highlight', item
);
5575 * Fetch an item by its label.
5577 * @param {string} label Label of the item to select.
5578 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5579 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
5581 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
5583 len
= this.items
.length
,
5584 filter
= this.getItemMatcher( label
, true );
5586 for ( i
= 0; i
< len
; i
++ ) {
5587 item
= this.items
[ i
];
5588 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5595 filter
= this.getItemMatcher( label
, false );
5596 for ( i
= 0; i
< len
; i
++ ) {
5597 item
= this.items
[ i
];
5598 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
5614 * Programmatically select an option by its label. If the item does not exist,
5615 * all options will be deselected.
5617 * @param {string} [label] Label of the item to select.
5618 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
5622 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
5623 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
5624 if ( label
=== undefined || !itemFromLabel
) {
5625 return this.selectItem();
5627 return this.selectItem( itemFromLabel
);
5631 * Programmatically select an option by its data. If the `data` parameter is omitted,
5632 * or if the item does not exist, all options will be deselected.
5634 * @param {Object|string} [data] Value of the item to select, omit to deselect all
5638 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
5639 var itemFromData
= this.getItemFromData( data
);
5640 if ( data
=== undefined || !itemFromData
) {
5641 return this.selectItem();
5643 return this.selectItem( itemFromData
);
5647 * Programmatically select an option by its reference. If the `item` parameter is omitted,
5648 * all options will be deselected.
5650 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
5654 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
5655 var i
, len
, selected
,
5658 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5659 selected
= this.items
[ i
] === item
;
5660 if ( this.items
[ i
].isSelected() !== selected
) {
5661 this.items
[ i
].setSelected( selected
);
5666 this.emit( 'select', item
);
5675 * Press is a state that occurs when a user mouses down on an item, but has not
5676 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
5677 * releases the mouse.
5679 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
5683 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
5684 var i
, len
, pressed
,
5687 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5688 pressed
= this.items
[ i
] === item
;
5689 if ( this.items
[ i
].isPressed() !== pressed
) {
5690 this.items
[ i
].setPressed( pressed
);
5695 this.emit( 'press', item
);
5704 * Note that ‘choose’ should never be modified programmatically. A user can choose
5705 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
5706 * use the #selectItem method.
5708 * This method is identical to #selectItem, but may vary in subclasses that take additional action
5709 * when users choose an item with the keyboard or mouse.
5711 * @param {OO.ui.OptionWidget} item Item to choose
5715 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
5717 this.selectItem( item
);
5718 this.emit( 'choose', item
);
5725 * Get an option by its position relative to the specified item (or to the start of the option array,
5726 * if item is `null`). The direction in which to search through the option array is specified with a
5727 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
5728 * `null` if there are no options in the array.
5730 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
5731 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
5732 * @param {Function} [filter] Only consider items for which this function returns
5733 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
5734 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
5736 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
5737 var currentIndex
, nextIndex
, i
,
5738 increase
= direction
> 0 ? 1 : -1,
5739 len
= this.items
.length
;
5741 if ( item
instanceof OO
.ui
.OptionWidget
) {
5742 currentIndex
= this.items
.indexOf( item
);
5743 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
5745 // If no item is selected and moving forward, start at the beginning.
5746 // If moving backward, start at the end.
5747 nextIndex
= direction
> 0 ? 0 : len
- 1;
5750 for ( i
= 0; i
< len
; i
++ ) {
5751 item
= this.items
[ nextIndex
];
5753 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
5754 ( !filter
|| filter( item
) )
5758 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
5764 * Get the next selectable item or `null` if there are no selectable items.
5765 * Disabled options and menu-section markers and breaks are not selectable.
5767 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
5769 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
5770 return this.getRelativeSelectableItem( null, 1 );
5774 * Add an array of options to the select. Optionally, an index number can be used to
5775 * specify an insertion point.
5777 * @param {OO.ui.OptionWidget[]} items Items to add
5778 * @param {number} [index] Index to insert items after
5782 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
5784 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
5786 // Always provide an index, even if it was omitted
5787 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
5793 * Remove the specified array of options from the select. Options will be detached
5794 * from the DOM, not removed, so they can be reused later. To remove all options from
5795 * the select, you may wish to use the #clearItems method instead.
5797 * @param {OO.ui.OptionWidget[]} items Items to remove
5801 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
5804 // Deselect items being removed
5805 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
5807 if ( item
.isSelected() ) {
5808 this.selectItem( null );
5813 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
5815 this.emit( 'remove', items
);
5821 * Clear all options from the select. Options will be detached from the DOM, not removed,
5822 * so that they can be reused later. To remove a subset of options from the select, use
5823 * the #removeItems method.
5828 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
5829 var items
= this.items
.slice();
5832 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
5835 this.selectItem( null );
5837 this.emit( 'remove', items
);
5843 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
5844 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
5845 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
5846 * options. For more information about options and selects, please see the
5847 * [OOjs UI documentation on MediaWiki][1].
5850 * // Decorated options in a select widget
5851 * var select = new OO.ui.SelectWidget( {
5853 * new OO.ui.DecoratedOptionWidget( {
5855 * label: 'Option with icon',
5858 * new OO.ui.DecoratedOptionWidget( {
5860 * label: 'Option with indicator',
5865 * $( 'body' ).append( select.$element );
5867 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5870 * @extends OO.ui.OptionWidget
5871 * @mixins OO.ui.mixin.IconElement
5872 * @mixins OO.ui.mixin.IndicatorElement
5875 * @param {Object} [config] Configuration options
5877 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
5878 // Parent constructor
5879 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
5881 // Mixin constructors
5882 OO
.ui
.mixin
.IconElement
.call( this, config
);
5883 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
5887 .addClass( 'oo-ui-decoratedOptionWidget' )
5888 .prepend( this.$icon
)
5889 .append( this.$indicator
);
5894 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
5895 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
5896 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
5899 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
5900 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
5901 * the [OOjs UI documentation on MediaWiki] [1] for more information.
5903 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
5906 * @extends OO.ui.DecoratedOptionWidget
5909 * @param {Object} [config] Configuration options
5911 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
5912 // Configuration initialization
5913 config
= $.extend( { icon
: 'check' }, config
);
5915 // Parent constructor
5916 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
5920 .attr( 'role', 'menuitem' )
5921 .addClass( 'oo-ui-menuOptionWidget' );
5926 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5928 /* Static Properties */
5930 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
5933 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
5934 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
5937 * var myDropdown = new OO.ui.DropdownWidget( {
5940 * new OO.ui.MenuSectionOptionWidget( {
5943 * new OO.ui.MenuOptionWidget( {
5945 * label: 'Welsh Corgi'
5947 * new OO.ui.MenuOptionWidget( {
5949 * label: 'Standard Poodle'
5951 * new OO.ui.MenuSectionOptionWidget( {
5954 * new OO.ui.MenuOptionWidget( {
5961 * $( 'body' ).append( myDropdown.$element );
5964 * @extends OO.ui.DecoratedOptionWidget
5967 * @param {Object} [config] Configuration options
5969 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
5970 // Parent constructor
5971 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
5974 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' );
5979 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
5981 /* Static Properties */
5983 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
5985 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
5988 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
5989 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
5990 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
5991 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
5992 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
5993 * and customized to be opened, closed, and displayed as needed.
5995 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
5996 * mouse outside the menu.
5998 * Menus also have support for keyboard interaction:
6000 * - Enter/Return key: choose and select a menu option
6001 * - Up-arrow key: highlight the previous menu option
6002 * - Down-arrow key: highlight the next menu option
6003 * - Esc key: hide the menu
6005 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6006 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6009 * @extends OO.ui.SelectWidget
6010 * @mixins OO.ui.mixin.ClippableElement
6013 * @param {Object} [config] Configuration options
6014 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6015 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6016 * and {@link OO.ui.mixin.LookupElement LookupElement}
6017 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6018 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6019 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6020 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6021 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6022 * that button, unless the button (or its parent widget) is passed in here.
6023 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6024 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6026 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6027 // Configuration initialization
6028 config
= config
|| {};
6030 // Parent constructor
6031 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6033 // Mixin constructors
6034 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6037 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6038 this.filterFromInput
= !!config
.filterFromInput
;
6039 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6040 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6041 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6042 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6046 .addClass( 'oo-ui-menuSelectWidget' )
6047 .attr( 'role', 'menu' );
6049 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6050 // that reference properties not initialized at that time of parent class construction
6051 // TODO: Find a better way to handle post-constructor setup
6052 this.visible
= false;
6053 this.$element
.addClass( 'oo-ui-element-hidden' );
6058 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6059 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6064 * Handles document mouse down events.
6067 * @param {MouseEvent} e Mouse down event
6069 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6071 !OO
.ui
.contains( this.$element
[ 0 ], e
.target
, true ) &&
6072 ( !this.$widget
|| !OO
.ui
.contains( this.$widget
[ 0 ], e
.target
, true ) )
6074 this.toggle( false );
6081 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
6082 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6084 if ( !this.isDisabled() && this.isVisible() ) {
6085 switch ( e
.keyCode
) {
6086 case OO
.ui
.Keys
.LEFT
:
6087 case OO
.ui
.Keys
.RIGHT
:
6088 // Do nothing if a text field is associated, arrow keys will be handled natively
6089 if ( !this.$input
) {
6090 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6093 case OO
.ui
.Keys
.ESCAPE
:
6094 case OO
.ui
.Keys
.TAB
:
6095 if ( currentItem
) {
6096 currentItem
.setHighlighted( false );
6098 this.toggle( false );
6099 // Don't prevent tabbing away, prevent defocusing
6100 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
6102 e
.stopPropagation();
6106 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
6113 * Update menu item visibility after input changes.
6117 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
6119 len
= this.items
.length
,
6120 showAll
= !this.isVisible(),
6121 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() );
6123 for ( i
= 0; i
< len
; i
++ ) {
6124 item
= this.items
[ i
];
6125 if ( item
instanceof OO
.ui
.OptionWidget
) {
6126 item
.toggle( showAll
|| filter( item
) );
6130 // Reevaluate clipping
6137 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
6138 if ( this.$input
) {
6139 this.$input
.on( 'keydown', this.onKeyDownHandler
);
6141 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
6148 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
6149 if ( this.$input
) {
6150 this.$input
.off( 'keydown', this.onKeyDownHandler
);
6152 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
6159 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
6160 if ( this.$input
) {
6161 if ( this.filterFromInput
) {
6162 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6165 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
6172 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
6173 if ( this.$input
) {
6174 if ( this.filterFromInput
) {
6175 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
6176 this.updateItemVisibility();
6179 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
6186 * When a user chooses an item, the menu is closed.
6188 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
6189 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
6191 * @param {OO.ui.OptionWidget} item Item to choose
6194 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
6195 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
6196 this.toggle( false );
6203 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
6205 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
6207 // Reevaluate clipping
6216 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
6218 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
6220 // Reevaluate clipping
6229 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
6231 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
6233 // Reevaluate clipping
6242 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
6245 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
6246 change
= visible
!== this.isVisible();
6249 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
6253 this.bindKeyDownListener();
6254 this.bindKeyPressListener();
6256 this.toggleClipping( true );
6258 if ( this.getSelectedItem() ) {
6259 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
6263 if ( this.autoHide
) {
6264 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6267 this.unbindKeyDownListener();
6268 this.unbindKeyPressListener();
6269 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
6270 this.toggleClipping( false );
6278 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
6279 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
6280 * users can interact with it.
6282 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6283 * OO.ui.DropdownInputWidget instead.
6286 * // Example: A DropdownWidget with a menu that contains three options
6287 * var dropDown = new OO.ui.DropdownWidget( {
6288 * label: 'Dropdown menu: Select a menu option',
6291 * new OO.ui.MenuOptionWidget( {
6295 * new OO.ui.MenuOptionWidget( {
6299 * new OO.ui.MenuOptionWidget( {
6307 * $( 'body' ).append( dropDown.$element );
6309 * dropDown.getMenu().selectItemByData( 'b' );
6311 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
6313 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
6315 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6318 * @extends OO.ui.Widget
6319 * @mixins OO.ui.mixin.IconElement
6320 * @mixins OO.ui.mixin.IndicatorElement
6321 * @mixins OO.ui.mixin.LabelElement
6322 * @mixins OO.ui.mixin.TitledElement
6323 * @mixins OO.ui.mixin.TabIndexedElement
6326 * @param {Object} [config] Configuration options
6327 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget}
6328 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
6329 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
6330 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
6332 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
6333 // Configuration initialization
6334 config
= $.extend( { indicator
: 'down' }, config
);
6336 // Parent constructor
6337 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
6339 // Properties (must be set before TabIndexedElement constructor call)
6340 this.$handle
= this.$( '<span>' );
6341 this.$overlay
= config
.$overlay
|| this.$element
;
6343 // Mixin constructors
6344 OO
.ui
.mixin
.IconElement
.call( this, config
);
6345 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6346 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6347 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
6348 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
6351 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend( {
6353 $container
: this.$element
6358 click
: this.onClick
.bind( this ),
6359 keydown
: this.onKeyDown
.bind( this ),
6360 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
6361 keypress
: this.menu
.onKeyPressHandler
,
6362 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
6364 this.menu
.connect( this, {
6365 select
: 'onMenuSelect',
6366 toggle
: 'onMenuToggle'
6371 .addClass( 'oo-ui-dropdownWidget-handle' )
6372 .append( this.$icon
, this.$label
, this.$indicator
);
6374 .addClass( 'oo-ui-dropdownWidget' )
6375 .append( this.$handle
);
6376 this.$overlay
.append( this.menu
.$element
);
6381 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
6382 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
6383 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
6384 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
6385 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
6386 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6393 * @return {OO.ui.MenuSelectWidget} Menu of widget
6395 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
6400 * Handles menu select events.
6403 * @param {OO.ui.MenuOptionWidget} item Selected menu item
6405 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
6409 this.setLabel( null );
6413 selectedLabel
= item
.getLabel();
6415 // If the label is a DOM element, clone it, because setLabel will append() it
6416 if ( selectedLabel
instanceof jQuery
) {
6417 selectedLabel
= selectedLabel
.clone();
6420 this.setLabel( selectedLabel
);
6424 * Handle menu toggle events.
6427 * @param {boolean} isVisible Menu toggle event
6429 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
6430 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
6434 * Handle mouse click events.
6437 * @param {jQuery.Event} e Mouse click event
6439 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
6440 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6447 * Handle key down events.
6450 * @param {jQuery.Event} e Key down event
6452 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
6454 !this.isDisabled() &&
6456 e
.which
=== OO
.ui
.Keys
.ENTER
||
6458 !this.menu
.isVisible() &&
6460 e
.which
=== OO
.ui
.Keys
.SPACE
||
6461 e
.which
=== OO
.ui
.Keys
.UP
||
6462 e
.which
=== OO
.ui
.Keys
.DOWN
6473 * RadioOptionWidget is an option widget that looks like a radio button.
6474 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
6475 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6477 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6480 * @extends OO.ui.OptionWidget
6483 * @param {Object} [config] Configuration options
6485 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
6486 // Configuration initialization
6487 config
= config
|| {};
6489 // Properties (must be done before parent constructor which calls #setDisabled)
6490 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
6492 // Parent constructor
6493 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
6496 // Remove implicit role, we're handling it ourselves
6497 this.radio
.$input
.attr( 'role', 'presentation' );
6499 .addClass( 'oo-ui-radioOptionWidget' )
6500 .attr( 'role', 'radio' )
6501 .attr( 'aria-checked', 'false' )
6502 .removeAttr( 'aria-selected' )
6503 .prepend( this.radio
.$element
);
6508 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
6510 /* Static Properties */
6512 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
6514 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
6516 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
6518 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
6525 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
6526 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6528 this.radio
.setSelected( state
);
6530 .attr( 'aria-checked', state
.toString() )
6531 .removeAttr( 'aria-selected' );
6539 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
6540 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6542 this.radio
.setDisabled( this.isDisabled() );
6548 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
6549 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
6550 * an interface for adding, removing and selecting options.
6551 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6553 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6554 * OO.ui.RadioSelectInputWidget instead.
6557 * // A RadioSelectWidget with RadioOptions.
6558 * var option1 = new OO.ui.RadioOptionWidget( {
6560 * label: 'Selected radio option'
6563 * var option2 = new OO.ui.RadioOptionWidget( {
6565 * label: 'Unselected radio option'
6568 * var radioSelect=new OO.ui.RadioSelectWidget( {
6569 * items: [ option1, option2 ]
6572 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
6573 * radioSelect.selectItem( option1 );
6575 * $( 'body' ).append( radioSelect.$element );
6577 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6581 * @extends OO.ui.SelectWidget
6582 * @mixins OO.ui.mixin.TabIndexedElement
6585 * @param {Object} [config] Configuration options
6587 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
6588 // Parent constructor
6589 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
6591 // Mixin constructors
6592 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
6596 focus
: this.bindKeyDownListener
.bind( this ),
6597 blur
: this.unbindKeyDownListener
.bind( this )
6602 .addClass( 'oo-ui-radioSelectWidget' )
6603 .attr( 'role', 'radiogroup' );
6608 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
6609 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
6612 * MultioptionWidgets are special elements that can be selected and configured with data. The
6613 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
6614 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
6615 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
6617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
6620 * @extends OO.ui.Widget
6621 * @mixins OO.ui.mixin.ItemWidget
6622 * @mixins OO.ui.mixin.LabelElement
6625 * @param {Object} [config] Configuration options
6626 * @cfg {boolean} [selected=false] Whether the option is initially selected
6628 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
6629 // Configuration initialization
6630 config
= config
|| {};
6632 // Parent constructor
6633 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
6635 // Mixin constructors
6636 OO
.ui
.mixin
.ItemWidget
.call( this );
6637 OO
.ui
.mixin
.LabelElement
.call( this, config
);
6640 this.selected
= null;
6644 .addClass( 'oo-ui-multioptionWidget' )
6645 .append( this.$label
);
6646 this.setSelected( config
.selected
);
6651 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
6652 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
6653 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
6660 * A change event is emitted when the selected state of the option changes.
6662 * @param {boolean} selected Whether the option is now selected
6668 * Check if the option is selected.
6670 * @return {boolean} Item is selected
6672 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
6673 return this.selected
;
6677 * Set the option’s selected state. In general, all modifications to the selection
6678 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
6679 * method instead of this method.
6681 * @param {boolean} [state=false] Select option
6684 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
6686 if ( this.selected
!== state
) {
6687 this.selected
= state
;
6688 this.emit( 'change', state
);
6689 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
6695 * MultiselectWidget allows selecting multiple options from a list.
6697 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
6699 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6703 * @extends OO.ui.Widget
6704 * @mixins OO.ui.mixin.GroupWidget
6707 * @param {Object} [config] Configuration options
6708 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
6710 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
6711 // Parent constructor
6712 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
6714 // Configuration initialization
6715 config
= config
|| {};
6717 // Mixin constructors
6718 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
6721 this.aggregate( { change
: 'select' } );
6722 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
6723 // by GroupElement only when items are added/removed
6724 this.connect( this, { select
: [ 'emit', 'change' ] } );
6727 if ( config
.items
) {
6728 this.addItems( config
.items
);
6730 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
6731 this.$element
.addClass( 'oo-ui-multiselectWidget' )
6732 .append( this.$group
);
6737 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
6738 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
6745 * A change event is emitted when the set of items changes, or an item is selected or deselected.
6751 * A select event is emitted when an item is selected or deselected.
6757 * Get options that are selected.
6759 * @return {OO.ui.MultioptionWidget[]} Selected options
6761 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
6762 return this.items
.filter( function ( item
) {
6763 return item
.isSelected();
6768 * Get the data of options that are selected.
6770 * @return {Object[]|string[]} Values of selected options
6772 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
6773 return this.getSelectedItems().map( function ( item
) {
6779 * Select options by reference. Options not mentioned in the `items` array will be deselected.
6781 * @param {OO.ui.MultioptionWidget[]} items Items to select
6784 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
6785 this.items
.forEach( function ( item
) {
6786 var selected
= items
.indexOf( item
) !== -1;
6787 item
.setSelected( selected
);
6793 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
6795 * @param {Object[]|string[]} datas Values of items to select
6798 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
6801 items
= datas
.map( function ( data
) {
6802 return widget
.getItemFromData( data
);
6804 this.selectItems( items
);
6809 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
6810 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
6811 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
6813 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
6816 * @extends OO.ui.MultioptionWidget
6819 * @param {Object} [config] Configuration options
6821 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
6822 // Configuration initialization
6823 config
= config
|| {};
6825 // Properties (must be done before parent constructor which calls #setDisabled)
6826 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
6828 // Parent constructor
6829 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
6832 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
6833 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
6837 .addClass( 'oo-ui-checkboxMultioptionWidget' )
6838 .prepend( this.checkbox
.$element
);
6843 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
6845 /* Static Properties */
6847 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
6852 * Handle checkbox selected state change.
6856 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
6857 this.setSelected( this.checkbox
.isSelected() );
6863 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
6864 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
6865 this.checkbox
.setSelected( state
);
6872 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
6873 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
6874 this.checkbox
.setDisabled( this.isDisabled() );
6881 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
6882 this.checkbox
.focus();
6886 * Handle key down events.
6889 * @param {jQuery.Event} e
6891 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
6893 element
= this.getElementGroup(),
6896 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
6897 nextItem
= element
.getRelativeFocusableItem( this, -1 );
6898 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
6899 nextItem
= element
.getRelativeFocusableItem( this, 1 );
6909 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
6910 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
6911 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
6912 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6914 * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use
6915 * OO.ui.CheckboxMultiselectInputWidget instead.
6918 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
6919 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
6922 * label: 'Selected checkbox'
6925 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
6927 * label: 'Unselected checkbox'
6930 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
6931 * items: [ option1, option2 ]
6934 * $( 'body' ).append( multiselect.$element );
6936 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6939 * @extends OO.ui.MultiselectWidget
6942 * @param {Object} [config] Configuration options
6944 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
6945 // Parent constructor
6946 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
6949 this.$lastClicked
= null;
6952 this.$group
.on( 'click', this.onClick
.bind( this ) );
6956 .addClass( 'oo-ui-checkboxMultiselectWidget' );
6961 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
6966 * Get an option by its position relative to the specified item (or to the start of the option array,
6967 * if item is `null`). The direction in which to search through the option array is specified with a
6968 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6969 * `null` if there are no options in the array.
6971 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6972 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6973 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
6975 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
6976 var currentIndex
, nextIndex
, i
,
6977 increase
= direction
> 0 ? 1 : -1,
6978 len
= this.items
.length
;
6981 currentIndex
= this.items
.indexOf( item
);
6982 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6984 // If no item is selected and moving forward, start at the beginning.
6985 // If moving backward, start at the end.
6986 nextIndex
= direction
> 0 ? 0 : len
- 1;
6989 for ( i
= 0; i
< len
; i
++ ) {
6990 item
= this.items
[ nextIndex
];
6991 if ( item
&& !item
.isDisabled() ) {
6994 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
7000 * Handle click events on checkboxes.
7002 * @param {jQuery.Event} e
7004 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
7005 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
7006 $lastClicked
= this.$lastClicked
,
7007 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
7008 .not( '.oo-ui-widget-disabled' );
7010 // Allow selecting multiple options at once by Shift-clicking them
7011 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
7012 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
7013 lastClickedIndex
= $options
.index( $lastClicked
);
7014 nowClickedIndex
= $options
.index( $nowClicked
);
7015 // If it's the same item, either the user is being silly, or it's a fake event generated by the
7016 // browser. In either case we don't need custom handling.
7017 if ( nowClickedIndex
!== lastClickedIndex
) {
7019 wasSelected
= items
[ nowClickedIndex
].isSelected();
7020 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
7022 // This depends on the DOM order of the items and the order of the .items array being the same.
7023 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
7024 if ( !items
[ i
].isDisabled() ) {
7025 items
[ i
].setSelected( !wasSelected
);
7028 // For the now-clicked element, use immediate timeout to allow the browser to do its own
7029 // handling first, then set our value. The order in which events happen is different for
7030 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
7031 // non-click actions that change the checkboxes.
7033 setTimeout( function () {
7034 if ( !items
[ nowClickedIndex
].isDisabled() ) {
7035 items
[ nowClickedIndex
].setSelected( !wasSelected
);
7041 if ( $nowClicked
.length
) {
7042 this.$lastClicked
= $nowClicked
;
7047 * Element that will stick under a specified container, even when it is inserted elsewhere in the
7048 * document (for example, in a OO.ui.Window's $overlay).
7050 * The elements's position is automatically calculated and maintained when window is resized or the
7051 * page is scrolled. If you reposition the container manually, you have to call #position to make
7052 * sure the element is still placed correctly.
7054 * As positioning is only possible when both the element and the container are attached to the DOM
7055 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
7056 * the #toggle method to display a floating popup, for example.
7062 * @param {Object} [config] Configuration options
7063 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
7064 * @cfg {jQuery} [$floatableContainer] Node to position below
7066 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
7067 // Configuration initialization
7068 config
= config
|| {};
7071 this.$floatable
= null;
7072 this.$floatableContainer
= null;
7073 this.$floatableWindow
= null;
7074 this.$floatableClosestScrollable
= null;
7075 this.onFloatableScrollHandler
= this.position
.bind( this );
7076 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
7079 this.setFloatableContainer( config
.$floatableContainer
);
7080 this.setFloatableElement( config
.$floatable
|| this.$element
);
7086 * Set floatable element.
7088 * If an element is already set, it will be cleaned up before setting up the new element.
7090 * @param {jQuery} $floatable Element to make floatable
7092 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
7093 if ( this.$floatable
) {
7094 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
7095 this.$floatable
.css( { left
: '', top
: '' } );
7098 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
7103 * Set floatable container.
7105 * The element will be always positioned under the specified container.
7107 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
7109 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
7110 this.$floatableContainer
= $floatableContainer
;
7111 if ( this.$floatable
) {
7117 * Toggle positioning.
7119 * Do not turn positioning on until after the element is attached to the DOM and visible.
7121 * @param {boolean} [positioning] Enable positioning, omit to toggle
7124 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
7125 var closestScrollableOfContainer
, closestScrollableOfFloatable
;
7127 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
7129 if ( this.positioning
!== positioning
) {
7130 this.positioning
= positioning
;
7132 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
7133 closestScrollableOfFloatable
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatable
[ 0 ] );
7134 this.needsCustomPosition
= closestScrollableOfContainer
!== closestScrollableOfFloatable
;
7135 // If the scrollable is the root, we have to listen to scroll events
7136 // on the window because of browser inconsistencies.
7137 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
7138 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
7141 if ( positioning
) {
7142 this.$floatableWindow
= $( this.getElementWindow() );
7143 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
7145 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
7146 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
7148 // Initial position after visible
7151 if ( this.$floatableWindow
) {
7152 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
7153 this.$floatableWindow
= null;
7156 if ( this.$floatableClosestScrollable
) {
7157 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
7158 this.$floatableClosestScrollable
= null;
7161 this.$floatable
.css( { left
: '', top
: '' } );
7169 * Check whether the bottom edge of the given element is within the viewport of the given container.
7172 * @param {jQuery} $element
7173 * @param {jQuery} $container
7176 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
7177 var elemRect
, contRect
,
7178 leftEdgeInBounds
= false,
7179 bottomEdgeInBounds
= false,
7180 rightEdgeInBounds
= false;
7182 elemRect
= $element
[ 0 ].getBoundingClientRect();
7183 if ( $container
[ 0 ] === window
) {
7187 right
: document
.documentElement
.clientWidth
,
7188 bottom
: document
.documentElement
.clientHeight
7191 contRect
= $container
[ 0 ].getBoundingClientRect();
7194 // For completeness, if we still cared about topEdgeInBounds, that'd be:
7195 // elemRect.top >= contRect.top && elemRect.top <= contRect.bottom
7196 if ( elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
) {
7197 leftEdgeInBounds
= true;
7199 if ( elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
) {
7200 bottomEdgeInBounds
= true;
7202 if ( elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
) {
7203 rightEdgeInBounds
= true;
7206 // We only care that any part of the bottom edge is visible
7207 return bottomEdgeInBounds
&& ( leftEdgeInBounds
|| rightEdgeInBounds
);
7211 * Position the floatable below its container.
7213 * This should only be done when both of them are attached to the DOM and visible.
7217 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
7220 if ( !this.positioning
) {
7224 if ( !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
7225 this.$floatable
.addClass( 'oo-ui-floatableElement-hidden' );
7228 this.$floatable
.removeClass( 'oo-ui-floatableElement-hidden' );
7231 if ( !this.needsCustomPosition
) {
7235 pos
= OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, this.$floatable
.offsetParent() );
7237 // Position under container
7238 pos
.top
+= this.$floatableContainer
.height();
7239 this.$floatable
.css( pos
);
7241 // We updated the position, so re-evaluate the clipping state.
7242 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
7243 // will not notice the need to update itself.)
7244 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
7245 // it not listen to the right events in the right places?
7254 * FloatingMenuSelectWidget is a menu that will stick under a specified
7255 * container, even when it is inserted elsewhere in the document (for example,
7256 * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the
7257 * menu from being clipped too aggresively.
7259 * The menu's position is automatically calculated and maintained when the menu
7260 * is toggled or the window is resized.
7262 * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class.
7265 * @extends OO.ui.MenuSelectWidget
7266 * @mixins OO.ui.mixin.FloatableElement
7269 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
7270 * Deprecated, omit this parameter and specify `$container` instead.
7271 * @param {Object} [config] Configuration options
7272 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
7274 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
7275 // Allow 'inputWidget' parameter and config for backwards compatibility
7276 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
7277 config
= inputWidget
;
7278 inputWidget
= config
.inputWidget
;
7281 // Configuration initialization
7282 config
= config
|| {};
7284 // Parent constructor
7285 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, config
);
7287 // Properties (must be set before mixin constructors)
7288 this.inputWidget
= inputWidget
; // For backwards compatibility
7289 this.$container
= config
.$container
|| this.inputWidget
.$element
;
7291 // Mixins constructors
7292 OO
.ui
.mixin
.FloatableElement
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
7295 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
7296 // For backwards compatibility
7297 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
7302 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
7303 OO
.mixinClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
7305 // For backwards compatibility
7306 OO
.ui
.TextInputMenuSelectWidget
= OO
.ui
.FloatingMenuSelectWidget
;
7313 OO
.ui
.FloatingMenuSelectWidget
.prototype.toggle = function ( visible
) {
7315 visible
= visible
=== undefined ? !this.isVisible() : !!visible
;
7316 change
= visible
!== this.isVisible();
7318 if ( change
&& visible
) {
7319 // Make sure the width is set before the parent method runs.
7320 this.setIdealSize( this.$container
.width() );
7324 // This will call this.clip(), which is nonsensical since we're not positioned yet...
7325 OO
.ui
.FloatingMenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7328 this.togglePositioning( this.isVisible() );
7335 * Progress bars visually display the status of an operation, such as a download,
7336 * and can be either determinate or indeterminate:
7338 * - **determinate** process bars show the percent of an operation that is complete.
7340 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
7341 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
7342 * not use percentages.
7344 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
7347 * // Examples of determinate and indeterminate progress bars.
7348 * var progressBar1 = new OO.ui.ProgressBarWidget( {
7351 * var progressBar2 = new OO.ui.ProgressBarWidget();
7353 * // Create a FieldsetLayout to layout progress bars
7354 * var fieldset = new OO.ui.FieldsetLayout;
7355 * fieldset.addItems( [
7356 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
7357 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
7359 * $( 'body' ).append( fieldset.$element );
7362 * @extends OO.ui.Widget
7365 * @param {Object} [config] Configuration options
7366 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
7367 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
7368 * By default, the progress bar is indeterminate.
7370 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
7371 // Configuration initialization
7372 config
= config
|| {};
7374 // Parent constructor
7375 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
7378 this.$bar
= $( '<div>' );
7379 this.progress
= null;
7382 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
7383 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
7386 role
: 'progressbar',
7388 'aria-valuemax': 100
7390 .addClass( 'oo-ui-progressBarWidget' )
7391 .append( this.$bar
);
7396 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
7398 /* Static Properties */
7400 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
7405 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
7407 * @return {number|boolean} Progress percent
7409 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
7410 return this.progress
;
7414 * Set the percent of the process completed or `false` for an indeterminate process.
7416 * @param {number|boolean} progress Progress percent or `false` for indeterminate
7418 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
7419 this.progress
= progress
;
7421 if ( progress
!== false ) {
7422 this.$bar
.css( 'width', this.progress
+ '%' );
7423 this.$element
.attr( 'aria-valuenow', this.progress
);
7425 this.$bar
.css( 'width', '' );
7426 this.$element
.removeAttr( 'aria-valuenow' );
7428 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
7432 * InputWidget is the base class for all input widgets, which
7433 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
7434 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
7435 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
7437 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7441 * @extends OO.ui.Widget
7442 * @mixins OO.ui.mixin.FlaggedElement
7443 * @mixins OO.ui.mixin.TabIndexedElement
7444 * @mixins OO.ui.mixin.TitledElement
7445 * @mixins OO.ui.mixin.AccessKeyedElement
7448 * @param {Object} [config] Configuration options
7449 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
7450 * @cfg {string} [value=''] The value of the input.
7451 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
7452 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
7453 * before it is accepted.
7455 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
7456 // Configuration initialization
7457 config
= config
|| {};
7459 // Parent constructor
7460 OO
.ui
.InputWidget
.parent
.call( this, config
);
7463 // See #reusePreInfuseDOM about config.$input
7464 this.$input
= config
.$input
|| this.getInputElement( config
);
7466 this.inputFilter
= config
.inputFilter
;
7468 // Mixin constructors
7469 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
7470 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
7471 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7472 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
7475 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
7479 .addClass( 'oo-ui-inputWidget-input' )
7480 .attr( 'name', config
.name
)
7481 .prop( 'disabled', this.isDisabled() );
7483 .addClass( 'oo-ui-inputWidget' )
7484 .append( this.$input
);
7485 this.setValue( config
.value
);
7487 this.setDir( config
.dir
);
7493 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
7494 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
7495 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7496 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
7497 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
7499 /* Static Properties */
7501 OO
.ui
.InputWidget
.static.supportsSimpleLabel
= true;
7503 /* Static Methods */
7508 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
7509 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
7510 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
7511 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
7518 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7519 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7520 if ( config
.$input
&& config
.$input
.length
) {
7521 state
.value
= config
.$input
.val();
7522 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
7523 state
.focus
= config
.$input
.is( ':focus' );
7533 * A change event is emitted when the value of the input changes.
7535 * @param {string} value
7541 * Get input element.
7543 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
7544 * different circumstances. The element must have a `value` property (like form elements).
7547 * @param {Object} config Configuration options
7548 * @return {jQuery} Input element
7550 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
7551 return $( '<input>' );
7555 * Handle potentially value-changing events.
7558 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
7560 OO
.ui
.InputWidget
.prototype.onEdit = function () {
7562 if ( !this.isDisabled() ) {
7563 // Allow the stack to clear so the value will be updated
7564 setTimeout( function () {
7565 widget
.setValue( widget
.$input
.val() );
7571 * Get the value of the input.
7573 * @return {string} Input value
7575 OO
.ui
.InputWidget
.prototype.getValue = function () {
7576 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7577 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7578 var value
= this.$input
.val();
7579 if ( this.value
!== value
) {
7580 this.setValue( value
);
7586 * Set the directionality of the input, either RTL (right-to-left) or LTR (left-to-right).
7588 * @deprecated since v0.13.1; use #setDir directly
7589 * @param {boolean} isRTL Directionality is right-to-left
7592 OO
.ui
.InputWidget
.prototype.setRTL = function ( isRTL
) {
7593 this.setDir( isRTL
? 'rtl' : 'ltr' );
7598 * Set the directionality of the input.
7600 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
7603 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
7604 this.$input
.prop( 'dir', dir
);
7609 * Set the value of the input.
7611 * @param {string} value New value
7615 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
7616 value
= this.cleanUpValue( value
);
7617 // Update the DOM if it has changed. Note that with cleanUpValue, it
7618 // is possible for the DOM value to change without this.value changing.
7619 if ( this.$input
.val() !== value
) {
7620 this.$input
.val( value
);
7622 if ( this.value
!== value
) {
7624 this.emit( 'change', this.value
);
7630 * Clean up incoming value.
7632 * Ensures value is a string, and converts undefined and null to empty string.
7635 * @param {string} value Original value
7636 * @return {string} Cleaned up value
7638 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
7639 if ( value
=== undefined || value
=== null ) {
7641 } else if ( this.inputFilter
) {
7642 return this.inputFilter( String( value
) );
7644 return String( value
);
7649 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
7650 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
7653 OO
.ui
.InputWidget
.prototype.simulateLabelClick = function () {
7654 if ( !this.isDisabled() ) {
7655 if ( this.$input
.is( ':checkbox, :radio' ) ) {
7656 this.$input
.click();
7658 if ( this.$input
.is( ':input' ) ) {
7659 this.$input
[ 0 ].focus();
7667 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
7668 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
7669 if ( this.$input
) {
7670 this.$input
.prop( 'disabled', this.isDisabled() );
7680 OO
.ui
.InputWidget
.prototype.focus = function () {
7681 this.$input
[ 0 ].focus();
7690 OO
.ui
.InputWidget
.prototype.blur = function () {
7691 this.$input
[ 0 ].blur();
7698 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
7699 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7700 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
7701 this.setValue( state
.value
);
7703 if ( state
.focus
) {
7709 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
7710 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
7711 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
7712 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
7713 * [OOjs UI documentation on MediaWiki] [1] for more information.
7716 * // A ButtonInputWidget rendered as an HTML button, the default.
7717 * var button = new OO.ui.ButtonInputWidget( {
7718 * label: 'Input button',
7722 * $( 'body' ).append( button.$element );
7724 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
7727 * @extends OO.ui.InputWidget
7728 * @mixins OO.ui.mixin.ButtonElement
7729 * @mixins OO.ui.mixin.IconElement
7730 * @mixins OO.ui.mixin.IndicatorElement
7731 * @mixins OO.ui.mixin.LabelElement
7732 * @mixins OO.ui.mixin.TitledElement
7735 * @param {Object} [config] Configuration options
7736 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
7737 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
7738 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
7739 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
7740 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
7742 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
7743 // Configuration initialization
7744 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
7746 // See InputWidget#reusePreInfuseDOM about config.$input
7747 if ( config
.$input
) {
7748 config
.$input
.empty();
7751 // Properties (must be set before parent constructor, which calls #setValue)
7752 this.useInputTag
= config
.useInputTag
;
7754 // Parent constructor
7755 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
7757 // Mixin constructors
7758 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
7759 OO
.ui
.mixin
.IconElement
.call( this, config
);
7760 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7761 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7762 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
7765 if ( !config
.useInputTag
) {
7766 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
7768 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
7773 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
7774 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
7775 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
7776 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
7777 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
7778 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
7780 /* Static Properties */
7783 * Disable generating `<label>` elements for buttons. One would very rarely need additional label
7784 * for a button, and it's already a big clickable target, and it causes unexpected rendering.
7786 OO
.ui
.ButtonInputWidget
.static.supportsSimpleLabel
= false;
7794 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
7796 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
7797 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
7803 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
7805 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
7806 * text, or `null` for no label
7809 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
7810 if ( typeof label
=== 'function' ) {
7811 label
= OO
.ui
.resolveMsg( label
);
7814 if ( this.useInputTag
) {
7815 // Discard non-plaintext labels
7816 if ( typeof label
!== 'string' ) {
7820 this.$input
.val( label
);
7823 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
7827 * Set the value of the input.
7829 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
7830 * they do not support {@link #value values}.
7832 * @param {string} value New value
7835 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
7836 if ( !this.useInputTag
) {
7837 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
7843 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
7844 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
7845 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
7846 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
7848 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
7851 * // An example of selected, unselected, and disabled checkbox inputs
7852 * var checkbox1=new OO.ui.CheckboxInputWidget( {
7856 * var checkbox2=new OO.ui.CheckboxInputWidget( {
7859 * var checkbox3=new OO.ui.CheckboxInputWidget( {
7863 * // Create a fieldset layout with fields for each checkbox.
7864 * var fieldset = new OO.ui.FieldsetLayout( {
7865 * label: 'Checkboxes'
7867 * fieldset.addItems( [
7868 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
7869 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
7870 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
7872 * $( 'body' ).append( fieldset.$element );
7874 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
7877 * @extends OO.ui.InputWidget
7880 * @param {Object} [config] Configuration options
7881 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
7883 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
7884 // Configuration initialization
7885 config
= config
|| {};
7887 // Parent constructor
7888 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
7892 .addClass( 'oo-ui-checkboxInputWidget' )
7893 // Required for pretty styling in MediaWiki theme
7894 .append( $( '<span>' ) );
7895 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
7900 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
7902 /* Static Methods */
7907 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
7908 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
7909 state
.checked
= config
.$input
.prop( 'checked' );
7919 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
7920 return $( '<input>' ).attr( 'type', 'checkbox' );
7926 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
7928 if ( !this.isDisabled() ) {
7929 // Allow the stack to clear so the value will be updated
7930 setTimeout( function () {
7931 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
7937 * Set selection state of this checkbox.
7939 * @param {boolean} state `true` for selected
7942 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
7944 if ( this.selected
!== state
) {
7945 this.selected
= state
;
7946 this.$input
.prop( 'checked', this.selected
);
7947 this.emit( 'change', this.selected
);
7953 * Check if this checkbox is selected.
7955 * @return {boolean} Checkbox is selected
7957 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
7958 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
7959 // it, and we won't know unless they're kind enough to trigger a 'change' event.
7960 var selected
= this.$input
.prop( 'checked' );
7961 if ( this.selected
!== selected
) {
7962 this.setSelected( selected
);
7964 return this.selected
;
7970 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
7971 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
7972 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
7973 this.setSelected( state
.checked
);
7978 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
7979 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
7980 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
7981 * more information about input widgets.
7983 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
7984 * are no options. If no `value` configuration option is provided, the first option is selected.
7985 * If you need a state representing no value (no option being selected), use a DropdownWidget.
7987 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
7990 * // Example: A DropdownInputWidget with three options
7991 * var dropdownInput = new OO.ui.DropdownInputWidget( {
7993 * { data: 'a', label: 'First' },
7994 * { data: 'b', label: 'Second'},
7995 * { data: 'c', label: 'Third' }
7998 * $( 'body' ).append( dropdownInput.$element );
8000 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8003 * @extends OO.ui.InputWidget
8004 * @mixins OO.ui.mixin.TitledElement
8007 * @param {Object} [config] Configuration options
8008 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8009 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8011 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8012 // Configuration initialization
8013 config
= config
|| {};
8015 // See InputWidget#reusePreInfuseDOM about config.$input
8016 if ( config
.$input
) {
8017 config
.$input
.addClass( 'oo-ui-element-hidden' );
8020 // Properties (must be done before parent constructor which calls #setDisabled)
8021 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8023 // Parent constructor
8024 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8026 // Mixin constructors
8027 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8030 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8033 this.setOptions( config
.options
|| [] );
8035 .addClass( 'oo-ui-dropdownInputWidget' )
8036 .append( this.dropdownWidget
.$element
);
8041 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8042 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8050 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8051 return $( '<input>' ).attr( 'type', 'hidden' );
8055 * Handles menu select events.
8058 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8060 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8061 this.setValue( item
.getData() );
8067 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8068 value
= this.cleanUpValue( value
);
8069 this.dropdownWidget
.getMenu().selectItemByData( value
);
8070 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8077 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8078 this.dropdownWidget
.setDisabled( state
);
8079 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8084 * Set the options available for this input.
8086 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8089 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8091 value
= this.getValue(),
8094 // Rebuild the dropdown menu
8095 this.dropdownWidget
.getMenu()
8097 .addItems( options
.map( function ( opt
) {
8098 var optValue
= widget
.cleanUpValue( opt
.data
);
8099 return new OO
.ui
.MenuOptionWidget( {
8101 label
: opt
.label
!== undefined ? opt
.label
: optValue
8105 // Restore the previous value, or reset to something sensible
8106 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8107 // Previous value is still available, ensure consistency with the dropdown
8108 this.setValue( value
);
8110 // No longer valid, reset
8111 if ( options
.length
) {
8112 this.setValue( options
[ 0 ].data
);
8122 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8123 this.dropdownWidget
.getMenu().toggle( true );
8130 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8131 this.dropdownWidget
.getMenu().toggle( false );
8136 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8137 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8138 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8139 * please see the [OOjs UI documentation on MediaWiki][1].
8141 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8144 * // An example of selected, unselected, and disabled radio inputs
8145 * var radio1 = new OO.ui.RadioInputWidget( {
8149 * var radio2 = new OO.ui.RadioInputWidget( {
8152 * var radio3 = new OO.ui.RadioInputWidget( {
8156 * // Create a fieldset layout with fields for each radio button.
8157 * var fieldset = new OO.ui.FieldsetLayout( {
8158 * label: 'Radio inputs'
8160 * fieldset.addItems( [
8161 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8162 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8163 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8165 * $( 'body' ).append( fieldset.$element );
8167 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8170 * @extends OO.ui.InputWidget
8173 * @param {Object} [config] Configuration options
8174 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
8176 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
8177 // Configuration initialization
8178 config
= config
|| {};
8180 // Parent constructor
8181 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
8185 .addClass( 'oo-ui-radioInputWidget' )
8186 // Required for pretty styling in MediaWiki theme
8187 .append( $( '<span>' ) );
8188 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8193 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
8195 /* Static Methods */
8200 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8201 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8202 state
.checked
= config
.$input
.prop( 'checked' );
8212 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
8213 return $( '<input>' ).attr( 'type', 'radio' );
8219 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
8220 // RadioInputWidget doesn't track its state.
8224 * Set selection state of this radio button.
8226 * @param {boolean} state `true` for selected
8229 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
8230 // RadioInputWidget doesn't track its state.
8231 this.$input
.prop( 'checked', state
);
8236 * Check if this radio button is selected.
8238 * @return {boolean} Radio is selected
8240 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
8241 return this.$input
.prop( 'checked' );
8247 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8248 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8249 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8250 this.setSelected( state
.checked
);
8255 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
8256 * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8257 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8258 * more information about input widgets.
8260 * This and OO.ui.DropdownInputWidget support the same configuration options.
8263 * // Example: A RadioSelectInputWidget with three options
8264 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
8266 * { data: 'a', label: 'First' },
8267 * { data: 'b', label: 'Second'},
8268 * { data: 'c', label: 'Third' }
8271 * $( 'body' ).append( radioSelectInput.$element );
8273 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8276 * @extends OO.ui.InputWidget
8279 * @param {Object} [config] Configuration options
8280 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8282 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
8283 // Configuration initialization
8284 config
= config
|| {};
8286 // Properties (must be done before parent constructor which calls #setDisabled)
8287 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
8289 // Parent constructor
8290 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
8293 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
8296 this.setOptions( config
.options
|| [] );
8298 .addClass( 'oo-ui-radioSelectInputWidget' )
8299 .append( this.radioSelectWidget
.$element
);
8304 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
8306 /* Static Properties */
8308 OO
.ui
.RadioSelectInputWidget
.static.supportsSimpleLabel
= false;
8310 /* Static Methods */
8315 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8316 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8317 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
8324 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8325 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8326 // Cannot reuse the `<input type=radio>` set
8327 delete config
.$input
;
8337 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
8338 return $( '<input>' ).attr( 'type', 'hidden' );
8342 * Handles menu select events.
8345 * @param {OO.ui.RadioOptionWidget} item Selected menu item
8347 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
8348 this.setValue( item
.getData() );
8354 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
8355 value
= this.cleanUpValue( value
);
8356 this.radioSelectWidget
.selectItemByData( value
);
8357 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8364 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
8365 this.radioSelectWidget
.setDisabled( state
);
8366 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8371 * Set the options available for this input.
8373 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8376 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
8378 value
= this.getValue(),
8381 // Rebuild the radioSelect menu
8382 this.radioSelectWidget
8384 .addItems( options
.map( function ( opt
) {
8385 var optValue
= widget
.cleanUpValue( opt
.data
);
8386 return new OO
.ui
.RadioOptionWidget( {
8388 label
: opt
.label
!== undefined ? opt
.label
: optValue
8392 // Restore the previous value, or reset to something sensible
8393 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
8394 // Previous value is still available, ensure consistency with the radioSelect
8395 this.setValue( value
);
8397 // No longer valid, reset
8398 if ( options
.length
) {
8399 this.setValue( options
[ 0 ].data
);
8407 * CheckboxMultiselectInputWidget is a
8408 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
8409 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
8410 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
8411 * more information about input widgets.
8414 * // Example: A CheckboxMultiselectInputWidget with three options
8415 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
8417 * { data: 'a', label: 'First' },
8418 * { data: 'b', label: 'Second'},
8419 * { data: 'c', label: 'Third' }
8422 * $( 'body' ).append( multiselectInput.$element );
8424 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8427 * @extends OO.ui.InputWidget
8430 * @param {Object} [config] Configuration options
8431 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8433 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
8434 // Configuration initialization
8435 config
= config
|| {};
8437 // Properties (must be done before parent constructor which calls #setDisabled)
8438 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
8440 // Parent constructor
8441 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
8444 this.inputName
= config
.name
;
8448 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
8449 .append( this.checkboxMultiselectWidget
.$element
);
8450 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
8451 this.$input
.detach();
8452 this.setOptions( config
.options
|| [] );
8453 // Have to repeat this from parent, as we need options to be set up for this to make sense
8454 this.setValue( config
.value
);
8459 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
8461 /* Static Properties */
8463 OO
.ui
.CheckboxMultiselectInputWidget
.static.supportsSimpleLabel
= false;
8465 /* Static Methods */
8470 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8471 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8472 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8473 .toArray().map( function ( el
) { return el
.value
; } );
8480 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8481 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8482 // Cannot reuse the `<input type=checkbox>` set
8483 delete config
.$input
;
8493 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
8495 return $( '<div>' );
8501 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
8502 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
8503 .toArray().map( function ( el
) { return el
.value
; } );
8504 if ( this.value
!== value
) {
8505 this.setValue( value
);
8513 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
8514 value
= this.cleanUpValue( value
);
8515 this.checkboxMultiselectWidget
.selectItemsByData( value
);
8516 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
8521 * Clean up incoming value.
8523 * @param {string[]} value Original value
8524 * @return {string[]} Cleaned up value
8526 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
8529 if ( !Array
.isArray( value
) ) {
8532 for ( i
= 0; i
< value
.length
; i
++ ) {
8534 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
8535 // Remove options that we don't have here
8536 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
8539 cleanValue
.push( singleValue
);
8547 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
8548 this.checkboxMultiselectWidget
.setDisabled( state
);
8549 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8554 * Set the options available for this input.
8556 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8559 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
8562 // Rebuild the checkboxMultiselectWidget menu
8563 this.checkboxMultiselectWidget
8565 .addItems( options
.map( function ( opt
) {
8568 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
8569 item
= new OO
.ui
.CheckboxMultioptionWidget( {
8571 label
: opt
.label
!== undefined ? opt
.label
: optValue
8573 // Set the 'name' and 'value' for form submission
8574 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
8575 item
.checkbox
.setValue( optValue
);
8579 // Re-set the value, checking the checkboxes as needed.
8580 // This will also get rid of any stale options that we just removed.
8581 this.setValue( this.getValue() );
8587 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
8588 * size of the field as well as its presentation. In addition, these widgets can be configured
8589 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
8590 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
8591 * which modifies incoming values rather than validating them.
8592 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8594 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
8597 * // Example of a text input widget
8598 * var textInput = new OO.ui.TextInputWidget( {
8599 * value: 'Text input'
8601 * $( 'body' ).append( textInput.$element );
8603 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8606 * @extends OO.ui.InputWidget
8607 * @mixins OO.ui.mixin.IconElement
8608 * @mixins OO.ui.mixin.IndicatorElement
8609 * @mixins OO.ui.mixin.PendingElement
8610 * @mixins OO.ui.mixin.LabelElement
8613 * @param {Object} [config] Configuration options
8614 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search',
8615 * 'email', 'url', 'date' or 'number'. Ignored if `multiline` is true.
8617 * Some values of `type` result in additional behaviors:
8619 * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator
8620 * empties the text field
8621 * @cfg {string} [placeholder] Placeholder text
8622 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
8623 * instruct the browser to focus this widget.
8624 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
8625 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
8626 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8627 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
8628 * specifies minimum number of rows to display.
8629 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
8630 * Use the #maxRows config to specify a maximum number of displayed rows.
8631 * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true.
8632 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
8633 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
8634 * the value or placeholder text: `'before'` or `'after'`
8635 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
8636 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
8637 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
8638 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
8639 * (the value must contain only numbers); when RegExp, a regular expression that must match the
8640 * value for it to be considered valid; when Function, a function receiving the value as parameter
8641 * that must return true, or promise resolving to true, for it to be considered valid.
8643 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
8644 // Configuration initialization
8645 config
= $.extend( {
8647 labelPosition
: 'after'
8649 if ( config
.type
=== 'search' ) {
8650 if ( config
.icon
=== undefined ) {
8651 config
.icon
= 'search';
8653 // indicator: 'clear' is set dynamically later, depending on value
8655 if ( config
.required
) {
8656 if ( config
.indicator
=== undefined ) {
8657 config
.indicator
= 'required';
8661 // Parent constructor
8662 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
8664 // Mixin constructors
8665 OO
.ui
.mixin
.IconElement
.call( this, config
);
8666 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8667 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
8668 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8671 this.type
= this.getSaneType( config
);
8672 this.readOnly
= false;
8673 this.multiline
= !!config
.multiline
;
8674 this.autosize
= !!config
.autosize
;
8675 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
8676 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
8677 this.validate
= null;
8678 this.styleHeight
= null;
8679 this.scrollWidth
= null;
8681 // Clone for resizing
8682 if ( this.autosize
) {
8683 this.$clone
= this.$input
8685 .insertAfter( this.$input
)
8686 .attr( 'aria-hidden', 'true' )
8687 .addClass( 'oo-ui-element-hidden' );
8690 this.setValidation( config
.validate
);
8691 this.setLabelPosition( config
.labelPosition
);
8695 keypress
: this.onKeyPress
.bind( this ),
8696 blur
: this.onBlur
.bind( this ),
8697 focus
: this.onFocus
.bind( this )
8700 focus
: this.onElementAttach
.bind( this )
8702 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
8703 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
8704 this.on( 'labelChange', this.updatePosition
.bind( this ) );
8705 this.connect( this, {
8707 disable
: 'onDisable'
8709 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
8713 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
8714 .append( this.$icon
, this.$indicator
);
8715 this.setReadOnly( !!config
.readOnly
);
8716 this.updateSearchIndicator();
8717 if ( config
.placeholder
!== undefined ) {
8718 this.$input
.attr( 'placeholder', config
.placeholder
);
8720 if ( config
.maxLength
!== undefined ) {
8721 this.$input
.attr( 'maxlength', config
.maxLength
);
8723 if ( config
.autofocus
) {
8724 this.$input
.attr( 'autofocus', 'autofocus' );
8726 if ( config
.required
) {
8727 this.$input
.attr( 'required', 'required' );
8728 this.$input
.attr( 'aria-required', 'true' );
8730 if ( config
.autocomplete
=== false ) {
8731 this.$input
.attr( 'autocomplete', 'off' );
8732 // Turning off autocompletion also disables "form caching" when the user navigates to a
8733 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
8735 beforeunload: function () {
8736 this.$input
.removeAttr( 'autocomplete' );
8738 pageshow: function () {
8739 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
8740 // whole page... it shouldn't hurt, though.
8741 this.$input
.attr( 'autocomplete', 'off' );
8745 if ( this.multiline
&& config
.rows
) {
8746 this.$input
.attr( 'rows', config
.rows
);
8748 if ( this.label
|| config
.autosize
) {
8749 this.installParentChangeDetector();
8755 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
8756 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
8757 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8758 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
8759 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
8761 /* Static Properties */
8763 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
8768 /* Static Methods */
8773 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8774 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8775 if ( config
.multiline
) {
8776 state
.scrollTop
= config
.$input
.scrollTop();
8784 * An `enter` event is emitted when the user presses 'enter' inside the text box.
8786 * Not emitted if the input is multiline.
8792 * A `resize` event is emitted when autosize is set and the widget resizes
8800 * Handle icon mouse down events.
8803 * @param {jQuery.Event} e Mouse down event
8805 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
8806 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8807 this.$input
[ 0 ].focus();
8813 * Handle indicator mouse down events.
8816 * @param {jQuery.Event} e Mouse down event
8818 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
8819 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
8820 if ( this.type
=== 'search' ) {
8821 // Clear the text field
8822 this.setValue( '' );
8824 this.$input
[ 0 ].focus();
8830 * Handle key press events.
8833 * @param {jQuery.Event} e Key press event
8834 * @fires enter If enter key is pressed and input is not multiline
8836 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
8837 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
8838 this.emit( 'enter', e
);
8843 * Handle blur events.
8846 * @param {jQuery.Event} e Blur event
8848 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
8849 this.setValidityFlag();
8853 * Handle focus events.
8856 * @param {jQuery.Event} e Focus event
8858 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
8859 this.setValidityFlag( true );
8863 * Handle element attach events.
8866 * @param {jQuery.Event} e Element attach event
8868 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
8869 // Any previously calculated size is now probably invalid if we reattached elsewhere
8870 this.valCache
= null;
8872 this.positionLabel();
8876 * Handle change events.
8878 * @param {string} value
8881 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
8882 this.updateSearchIndicator();
8887 * Handle debounced change events.
8889 * @param {string} value
8892 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
8893 this.setValidityFlag();
8897 * Handle disable events.
8899 * @param {boolean} disabled Element is disabled
8902 OO
.ui
.TextInputWidget
.prototype.onDisable = function () {
8903 this.updateSearchIndicator();
8907 * Check if the input is {@link #readOnly read-only}.
8911 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
8912 return this.readOnly
;
8916 * Set the {@link #readOnly read-only} state of the input.
8918 * @param {boolean} state Make input read-only
8921 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
8922 this.readOnly
= !!state
;
8923 this.$input
.prop( 'readOnly', this.readOnly
);
8924 this.updateSearchIndicator();
8929 * Support function for making #onElementAttach work across browsers.
8931 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
8932 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
8934 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
8935 * first time that the element gets attached to the documented.
8937 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
8938 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
8939 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
8942 if ( MutationObserver
) {
8943 // The new way. If only it wasn't so ugly.
8945 if ( this.$element
.closest( 'html' ).length
) {
8946 // Widget is attached already, do nothing. This breaks the functionality of this function when
8947 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
8948 // would require observation of the whole document, which would hurt performance of other,
8949 // more important code.
8953 // Find topmost node in the tree
8954 topmostNode
= this.$element
[ 0 ];
8955 while ( topmostNode
.parentNode
) {
8956 topmostNode
= topmostNode
.parentNode
;
8959 // We have no way to detect the $element being attached somewhere without observing the entire
8960 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
8961 // parent node of $element, and instead detect when $element is removed from it (and thus
8962 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
8963 // doesn't get attached, we end up back here and create the parent.
8965 mutationObserver
= new MutationObserver( function ( mutations
) {
8966 var i
, j
, removedNodes
;
8967 for ( i
= 0; i
< mutations
.length
; i
++ ) {
8968 removedNodes
= mutations
[ i
].removedNodes
;
8969 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
8970 if ( removedNodes
[ j
] === topmostNode
) {
8971 setTimeout( onRemove
, 0 );
8978 onRemove = function () {
8979 // If the node was attached somewhere else, report it
8980 if ( widget
.$element
.closest( 'html' ).length
) {
8981 widget
.onElementAttach();
8983 mutationObserver
.disconnect();
8984 widget
.installParentChangeDetector();
8987 // Create a fake parent and observe it
8988 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
8989 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
8991 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
8992 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
8993 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
8998 * Automatically adjust the size of the text input.
9000 * This only affects #multiline inputs that are {@link #autosize autosized}.
9005 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9006 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9007 idealHeight
, newHeight
, scrollWidth
, property
;
9009 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9010 if ( this.autosize
) {
9012 .val( this.$input
.val() )
9013 .attr( 'rows', this.minRows
)
9014 // Set inline height property to 0 to measure scroll height
9015 .css( 'height', 0 );
9017 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9019 this.valCache
= this.$input
.val();
9021 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9023 // Remove inline height property to measure natural heights
9024 this.$clone
.css( 'height', '' );
9025 innerHeight
= this.$clone
.innerHeight();
9026 outerHeight
= this.$clone
.outerHeight();
9028 // Measure max rows height
9030 .attr( 'rows', this.maxRows
)
9031 .css( 'height', 'auto' )
9033 maxInnerHeight
= this.$clone
.innerHeight();
9035 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9036 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9037 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9038 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9040 this.$clone
.addClass( 'oo-ui-element-hidden' );
9042 // Only apply inline height when expansion beyond natural height is needed
9043 // Use the difference between the inner and outer height as a buffer
9044 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9045 if ( newHeight
!== this.styleHeight
) {
9046 this.$input
.css( 'height', newHeight
);
9047 this.styleHeight
= newHeight
;
9048 this.emit( 'resize' );
9051 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9052 if ( scrollWidth
!== this.scrollWidth
) {
9053 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9055 this.$label
.css( { right
: '', left
: '' } );
9056 this.$indicator
.css( { right
: '', left
: '' } );
9058 if ( scrollWidth
) {
9059 this.$indicator
.css( property
, scrollWidth
);
9060 if ( this.labelPosition
=== 'after' ) {
9061 this.$label
.css( property
, scrollWidth
);
9065 this.scrollWidth
= scrollWidth
;
9066 this.positionLabel();
9076 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9077 if ( config
.multiline
) {
9078 return $( '<textarea>' );
9079 } else if ( this.getSaneType( config
) === 'number' ) {
9080 return $( '<input>' )
9081 .attr( 'step', 'any' )
9082 .attr( 'type', 'number' );
9084 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9089 * Get sanitized value for 'type' for given config.
9091 * @param {Object} config Configuration options
9092 * @return {string|null}
9095 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9096 var allowedTypes
= [
9105 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9109 * Check if the input supports multiple lines.
9113 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9114 return !!this.multiline
;
9118 * Check if the input automatically adjusts its size.
9122 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9123 return !!this.autosize
;
9127 * Focus the input and select a specified range within the text.
9129 * @param {number} from Select from offset
9130 * @param {number} [to] Select to offset, defaults to from
9133 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
9134 var isBackwards
, start
, end
,
9135 input
= this.$input
[ 0 ];
9139 isBackwards
= to
< from;
9140 start
= isBackwards
? to
: from;
9141 end
= isBackwards
? from : to
;
9146 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
9148 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
9149 // Rather than expensively check if the input is attached every time, just check
9150 // if it was the cause of an error being thrown. If not, rethrow the error.
9151 if ( this.getElementDocument().body
.contains( input
) ) {
9159 * Get an object describing the current selection range in a directional manner
9161 * @return {Object} Object containing 'from' and 'to' offsets
9163 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
9164 var input
= this.$input
[ 0 ],
9165 start
= input
.selectionStart
,
9166 end
= input
.selectionEnd
,
9167 isBackwards
= input
.selectionDirection
=== 'backward';
9170 from: isBackwards
? end
: start
,
9171 to
: isBackwards
? start
: end
9176 * Get the length of the text input value.
9178 * This could differ from the length of #getValue if the
9179 * value gets filtered
9181 * @return {number} Input length
9183 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
9184 return this.$input
[ 0 ].value
.length
;
9188 * Focus the input and select the entire text.
9192 OO
.ui
.TextInputWidget
.prototype.select = function () {
9193 return this.selectRange( 0, this.getInputLength() );
9197 * Focus the input and move the cursor to the start.
9201 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
9202 return this.selectRange( 0 );
9206 * Focus the input and move the cursor to the end.
9210 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
9211 return this.selectRange( this.getInputLength() );
9215 * Insert new content into the input.
9217 * @param {string} content Content to be inserted
9220 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
9222 range
= this.getRange(),
9223 value
= this.getValue();
9225 start
= Math
.min( range
.from, range
.to
);
9226 end
= Math
.max( range
.from, range
.to
);
9228 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
9229 this.selectRange( start
+ content
.length
);
9234 * Insert new content either side of a selection.
9236 * @param {string} pre Content to be inserted before the selection
9237 * @param {string} post Content to be inserted after the selection
9240 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
9242 range
= this.getRange(),
9243 offset
= pre
.length
;
9245 start
= Math
.min( range
.from, range
.to
);
9246 end
= Math
.max( range
.from, range
.to
);
9248 this.selectRange( start
).insertContent( pre
);
9249 this.selectRange( offset
+ end
).insertContent( post
);
9251 this.selectRange( offset
+ start
, offset
+ end
);
9256 * Set the validation pattern.
9258 * The validation pattern is either a regular expression, a function, or the symbolic name of a
9259 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
9260 * value must contain only numbers).
9262 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
9263 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
9265 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
9266 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
9267 this.validate
= validate
;
9269 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
9274 * Sets the 'invalid' flag appropriately.
9276 * @param {boolean} [isValid] Optionally override validation result
9278 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
9280 setFlag = function ( valid
) {
9282 widget
.$input
.attr( 'aria-invalid', 'true' );
9284 widget
.$input
.removeAttr( 'aria-invalid' );
9286 widget
.setFlags( { invalid
: !valid
} );
9289 if ( isValid
!== undefined ) {
9292 this.getValidity().then( function () {
9301 * Check if a value is valid.
9303 * This method returns a promise that resolves with a boolean `true` if the current value is
9304 * considered valid according to the supplied {@link #validate validation pattern}.
9306 * @deprecated since v0.12.3
9307 * @return {jQuery.Promise} A promise that resolves to a boolean `true` if the value is valid.
9309 OO
.ui
.TextInputWidget
.prototype.isValid = function () {
9312 if ( this.validate
instanceof Function
) {
9313 result
= this.validate( this.getValue() );
9314 if ( result
&& $.isFunction( result
.promise
) ) {
9315 return result
.promise();
9317 return $.Deferred().resolve( !!result
).promise();
9320 return $.Deferred().resolve( !!this.getValue().match( this.validate
) ).promise();
9325 * Get the validity of current value.
9327 * This method returns a promise that resolves if the value is valid and rejects if
9328 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
9330 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
9332 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
9335 function rejectOrResolve( valid
) {
9337 return $.Deferred().resolve().promise();
9339 return $.Deferred().reject().promise();
9343 if ( this.validate
instanceof Function
) {
9344 result
= this.validate( this.getValue() );
9345 if ( result
&& $.isFunction( result
.promise
) ) {
9346 return result
.promise().then( function ( valid
) {
9347 return rejectOrResolve( valid
);
9350 return rejectOrResolve( result
);
9353 return rejectOrResolve( this.getValue().match( this.validate
) );
9358 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
9360 * @param {string} labelPosition Label position, 'before' or 'after'
9363 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
9364 this.labelPosition
= labelPosition
;
9366 // If there is no label and we only change the position, #updatePosition is a no-op,
9367 // but it takes really a lot of work to do nothing.
9368 this.updatePosition();
9374 * Update the position of the inline label.
9376 * This method is called by #setLabelPosition, and can also be called on its own if
9377 * something causes the label to be mispositioned.
9381 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
9382 var after
= this.labelPosition
=== 'after';
9385 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
9386 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
9388 this.valCache
= null;
9389 this.scrollWidth
= null;
9391 this.positionLabel();
9397 * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is
9398 * already empty or when it's not editable.
9400 OO
.ui
.TextInputWidget
.prototype.updateSearchIndicator = function () {
9401 if ( this.type
=== 'search' ) {
9402 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
9403 this.setIndicator( null );
9405 this.setIndicator( 'clear' );
9411 * Position the label by setting the correct padding on the input.
9416 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
9417 var after
, rtl
, property
;
9420 // Clear old values if present
9422 'padding-right': '',
9427 this.$element
.append( this.$label
);
9429 this.$label
.detach();
9433 after
= this.labelPosition
=== 'after';
9434 rtl
= this.$element
.css( 'direction' ) === 'rtl';
9435 property
= after
=== rtl
? 'padding-left' : 'padding-right';
9437 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
9445 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9446 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9447 if ( state
.scrollTop
!== undefined ) {
9448 this.$input
.scrollTop( state
.scrollTop
);
9453 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
9454 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
9455 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
9457 * - by typing a value in the text input field. If the value exactly matches the value of a menu
9458 * option, that option will appear to be selected.
9459 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
9462 * This widget can be used inside a HTML form, such as a OO.ui.FormLayout.
9464 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
9467 * // Example: A ComboBoxInputWidget.
9468 * var comboBox = new OO.ui.ComboBoxInputWidget( {
9469 * label: 'ComboBoxInputWidget',
9470 * value: 'Option 1',
9473 * new OO.ui.MenuOptionWidget( {
9475 * label: 'Option One'
9477 * new OO.ui.MenuOptionWidget( {
9479 * label: 'Option Two'
9481 * new OO.ui.MenuOptionWidget( {
9483 * label: 'Option Three'
9485 * new OO.ui.MenuOptionWidget( {
9487 * label: 'Option Four'
9489 * new OO.ui.MenuOptionWidget( {
9491 * label: 'Option Five'
9496 * $( 'body' ).append( comboBox.$element );
9498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
9501 * @extends OO.ui.TextInputWidget
9504 * @param {Object} [config] Configuration options
9505 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9506 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}.
9507 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
9508 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
9509 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
9511 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
9512 // Configuration initialization
9513 config
= $.extend( {
9517 // For backwards-compatibility with ComboBoxWidget config
9518 $.extend( config
, config
.input
);
9520 // Parent constructor
9521 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
9524 this.$overlay
= config
.$overlay
|| this.$element
;
9525 this.menu
= new OO
.ui
.FloatingMenuSelectWidget( $.extend(
9529 $container
: this.$element
,
9530 disabled
: this.isDisabled()
9534 // For backwards-compatibility with ComboBoxWidget
9538 this.$indicator
.on( {
9539 click
: this.onIndicatorClick
.bind( this ),
9540 keypress
: this.onIndicatorKeyPress
.bind( this )
9542 this.connect( this, {
9543 change
: 'onInputChange',
9544 enter
: 'onInputEnter'
9546 this.menu
.connect( this, {
9547 choose
: 'onMenuChoose',
9548 add
: 'onMenuItemsChange',
9549 remove
: 'onMenuItemsChange'
9555 'aria-autocomplete': 'list'
9557 // Do not override options set via config.menu.items
9558 if ( config
.options
!== undefined ) {
9559 this.setOptions( config
.options
);
9561 // Extra class for backwards-compatibility with ComboBoxWidget
9562 this.$element
.addClass( 'oo-ui-comboBoxInputWidget oo-ui-comboBoxWidget' );
9563 this.$overlay
.append( this.menu
.$element
);
9564 this.onMenuItemsChange();
9569 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
9574 * Get the combobox's menu.
9576 * @return {OO.ui.FloatingMenuSelectWidget} Menu widget
9578 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
9583 * Get the combobox's text input widget.
9585 * @return {OO.ui.TextInputWidget} Text input widget
9587 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
9592 * Handle input change events.
9595 * @param {string} value New value
9597 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
9598 var match
= this.menu
.getItemFromData( value
);
9600 this.menu
.selectItem( match
);
9601 if ( this.menu
.getHighlightedItem() ) {
9602 this.menu
.highlightItem( match
);
9605 if ( !this.isDisabled() ) {
9606 this.menu
.toggle( true );
9611 * Handle mouse click events.
9614 * @param {jQuery.Event} e Mouse click event
9616 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorClick = function ( e
) {
9617 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9619 this.$input
[ 0 ].focus();
9625 * Handle key press events.
9628 * @param {jQuery.Event} e Key press event
9630 OO
.ui
.ComboBoxInputWidget
.prototype.onIndicatorKeyPress = function ( e
) {
9631 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
9633 this.$input
[ 0 ].focus();
9639 * Handle input enter events.
9643 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
9644 if ( !this.isDisabled() ) {
9645 this.menu
.toggle( false );
9650 * Handle menu choose events.
9653 * @param {OO.ui.OptionWidget} item Chosen item
9655 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
9656 this.setValue( item
.getData() );
9660 * Handle menu item change events.
9664 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
9665 var match
= this.menu
.getItemFromData( this.getValue() );
9666 this.menu
.selectItem( match
);
9667 if ( this.menu
.getHighlightedItem() ) {
9668 this.menu
.highlightItem( match
);
9670 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
9676 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
9678 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
9681 this.menu
.setDisabled( this.isDisabled() );
9688 * Set the options available for this input.
9690 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9693 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
9696 .addItems( options
.map( function ( opt
) {
9697 return new OO
.ui
.MenuOptionWidget( {
9699 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
9708 * @deprecated since 0.13.2; use OO.ui.ComboBoxInputWidget instead
9710 OO
.ui
.ComboBoxWidget
= OO
.ui
.ComboBoxInputWidget
;
9713 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
9714 * which is a widget that is specified by reference before any optional configuration settings.
9716 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
9718 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9719 * A left-alignment is used for forms with many fields.
9720 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9721 * A right-alignment is used for long but familiar forms which users tab through,
9722 * verifying the current field with a quick glance at the label.
9723 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9724 * that users fill out from top to bottom.
9725 * - **inline**: The label is placed after the field-widget and aligned to the left.
9726 * An inline-alignment is best used with checkboxes or radio buttons.
9728 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
9729 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
9731 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
9734 * @extends OO.ui.Layout
9735 * @mixins OO.ui.mixin.LabelElement
9736 * @mixins OO.ui.mixin.TitledElement
9739 * @param {OO.ui.Widget} fieldWidget Field widget
9740 * @param {Object} [config] Configuration options
9741 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
9742 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
9743 * The array may contain strings or OO.ui.HtmlSnippet instances.
9744 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
9745 * The array may contain strings or OO.ui.HtmlSnippet instances.
9746 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
9747 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
9748 * For important messages, you are advised to use `notices`, as they are always shown.
9750 * @throws {Error} An error is thrown if no widget is specified
9752 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
9753 var hasInputWidget
, div
;
9755 // Allow passing positional parameters inside the config object
9756 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
9757 config
= fieldWidget
;
9758 fieldWidget
= config
.fieldWidget
;
9761 // Make sure we have required constructor arguments
9762 if ( fieldWidget
=== undefined ) {
9763 throw new Error( 'Widget not found' );
9766 hasInputWidget
= fieldWidget
.constructor.static.supportsSimpleLabel
;
9768 // Configuration initialization
9769 config
= $.extend( { align
: 'left' }, config
);
9771 // Parent constructor
9772 OO
.ui
.FieldLayout
.parent
.call( this, config
);
9774 // Mixin constructors
9775 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9776 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
9779 this.fieldWidget
= fieldWidget
;
9782 this.$field
= $( '<div>' );
9783 this.$messages
= $( '<ul>' );
9784 this.$body
= $( '<' + ( hasInputWidget
? 'label' : 'div' ) + '>' );
9786 if ( config
.help
) {
9787 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
9788 classes
: [ 'oo-ui-fieldLayout-help' ],
9794 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
9795 div
.html( config
.help
.toString() );
9797 div
.text( config
.help
);
9799 this.popupButtonWidget
.getPopup().$body
.append(
9800 div
.addClass( 'oo-ui-fieldLayout-help-content' )
9802 this.$help
= this.popupButtonWidget
.$element
;
9804 this.$help
= $( [] );
9808 if ( hasInputWidget
) {
9809 this.$label
.on( 'click', this.onLabelClick
.bind( this ) );
9811 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
9815 .addClass( 'oo-ui-fieldLayout' )
9816 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
9817 .append( this.$help
, this.$body
);
9818 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
9819 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
9821 .addClass( 'oo-ui-fieldLayout-field' )
9822 .append( this.fieldWidget
.$element
);
9824 this.setErrors( config
.errors
|| [] );
9825 this.setNotices( config
.notices
|| [] );
9826 this.setAlignment( config
.align
);
9831 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
9832 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
9833 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
9838 * Handle field disable events.
9841 * @param {boolean} value Field is disabled
9843 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
9844 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
9848 * Handle label mouse click events.
9851 * @param {jQuery.Event} e Mouse click event
9853 OO
.ui
.FieldLayout
.prototype.onLabelClick = function () {
9854 this.fieldWidget
.simulateLabelClick();
9859 * Get the widget contained by the field.
9861 * @return {OO.ui.Widget} Field widget
9863 OO
.ui
.FieldLayout
.prototype.getField = function () {
9864 return this.fieldWidget
;
9869 * @param {string} kind 'error' or 'notice'
9870 * @param {string|OO.ui.HtmlSnippet} text
9873 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
9874 var $listItem
, $icon
, message
;
9875 $listItem
= $( '<li>' );
9876 if ( kind
=== 'error' ) {
9877 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
9878 } else if ( kind
=== 'notice' ) {
9879 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
9883 message
= new OO
.ui
.LabelWidget( { label
: text
} );
9885 .append( $icon
, message
.$element
)
9886 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
9891 * Set the field alignment mode.
9894 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
9897 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
9898 if ( value
!== this.align
) {
9899 // Default to 'left'
9900 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
9904 if ( value
=== 'inline' ) {
9905 this.$body
.append( this.$field
, this.$label
);
9907 this.$body
.append( this.$label
, this.$field
);
9909 // Set classes. The following classes can be used here:
9910 // * oo-ui-fieldLayout-align-left
9911 // * oo-ui-fieldLayout-align-right
9912 // * oo-ui-fieldLayout-align-top
9913 // * oo-ui-fieldLayout-align-inline
9915 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
9917 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
9925 * Set the list of error messages.
9927 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
9928 * The array may contain strings or OO.ui.HtmlSnippet instances.
9931 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
9932 this.errors
= errors
.slice();
9933 this.updateMessages();
9938 * Set the list of notice messages.
9940 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
9941 * The array may contain strings or OO.ui.HtmlSnippet instances.
9944 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
9945 this.notices
= notices
.slice();
9946 this.updateMessages();
9951 * Update the rendering of error and notice messages.
9955 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
9957 this.$messages
.empty();
9959 if ( this.errors
.length
|| this.notices
.length
) {
9960 this.$body
.after( this.$messages
);
9962 this.$messages
.remove();
9966 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
9967 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
9969 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
9970 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
9975 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
9976 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
9977 * is required and is specified before any optional configuration settings.
9979 * Labels can be aligned in one of four ways:
9981 * - **left**: The label is placed before the field-widget and aligned with the left margin.
9982 * A left-alignment is used for forms with many fields.
9983 * - **right**: The label is placed before the field-widget and aligned to the right margin.
9984 * A right-alignment is used for long but familiar forms which users tab through,
9985 * verifying the current field with a quick glance at the label.
9986 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
9987 * that users fill out from top to bottom.
9988 * - **inline**: The label is placed after the field-widget and aligned to the left.
9989 * An inline-alignment is best used with checkboxes or radio buttons.
9991 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
9992 * text is specified.
9995 * // Example of an ActionFieldLayout
9996 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
9997 * new OO.ui.TextInputWidget( {
9998 * placeholder: 'Field widget'
10000 * new OO.ui.ButtonWidget( {
10004 * label: 'An ActionFieldLayout. This label is aligned top',
10006 * help: 'This is help text'
10010 * $( 'body' ).append( actionFieldLayout.$element );
10013 * @extends OO.ui.FieldLayout
10016 * @param {OO.ui.Widget} fieldWidget Field widget
10017 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10019 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10020 // Allow passing positional parameters inside the config object
10021 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10022 config
= fieldWidget
;
10023 fieldWidget
= config
.fieldWidget
;
10024 buttonWidget
= config
.buttonWidget
;
10027 // Parent constructor
10028 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10031 this.buttonWidget
= buttonWidget
;
10032 this.$button
= $( '<div>' );
10033 this.$input
= $( '<div>' );
10037 .addClass( 'oo-ui-actionFieldLayout' );
10039 .addClass( 'oo-ui-actionFieldLayout-button' )
10040 .append( this.buttonWidget
.$element
);
10042 .addClass( 'oo-ui-actionFieldLayout-input' )
10043 .append( this.fieldWidget
.$element
);
10045 .append( this.$input
, this.$button
);
10050 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
10053 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
10054 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
10055 * configured with a label as well. For more information and examples,
10056 * please see the [OOjs UI documentation on MediaWiki][1].
10059 * // Example of a fieldset layout
10060 * var input1 = new OO.ui.TextInputWidget( {
10061 * placeholder: 'A text input field'
10064 * var input2 = new OO.ui.TextInputWidget( {
10065 * placeholder: 'A text input field'
10068 * var fieldset = new OO.ui.FieldsetLayout( {
10069 * label: 'Example of a fieldset layout'
10072 * fieldset.addItems( [
10073 * new OO.ui.FieldLayout( input1, {
10074 * label: 'Field One'
10076 * new OO.ui.FieldLayout( input2, {
10077 * label: 'Field Two'
10080 * $( 'body' ).append( fieldset.$element );
10082 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10085 * @extends OO.ui.Layout
10086 * @mixins OO.ui.mixin.IconElement
10087 * @mixins OO.ui.mixin.LabelElement
10088 * @mixins OO.ui.mixin.GroupElement
10091 * @param {Object} [config] Configuration options
10092 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
10094 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
10095 // Configuration initialization
10096 config
= config
|| {};
10098 // Parent constructor
10099 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
10101 // Mixin constructors
10102 OO
.ui
.mixin
.IconElement
.call( this, config
);
10103 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<legend>' ) } ) );
10104 OO
.ui
.mixin
.GroupElement
.call( this, config
);
10106 if ( config
.help
) {
10107 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10108 classes
: [ 'oo-ui-fieldsetLayout-help' ],
10113 this.popupButtonWidget
.getPopup().$body
.append(
10115 .text( config
.help
)
10116 .addClass( 'oo-ui-fieldsetLayout-help-content' )
10118 this.$help
= this.popupButtonWidget
.$element
;
10120 this.$help
= $( [] );
10124 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
10126 .addClass( 'oo-ui-fieldsetLayout' )
10127 .prepend( this.$label
, this.$help
, this.$icon
, this.$group
);
10128 if ( Array
.isArray( config
.items
) ) {
10129 this.addItems( config
.items
);
10135 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
10136 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
10137 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
10138 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
10140 /* Static Properties */
10142 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
10145 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
10146 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
10147 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
10148 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10150 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
10151 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
10152 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
10153 * some fancier controls. Some controls have both regular and InputWidget variants, for example
10154 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
10155 * often have simplified APIs to match the capabilities of HTML forms.
10156 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
10158 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
10159 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10162 * // Example of a form layout that wraps a fieldset layout
10163 * var input1 = new OO.ui.TextInputWidget( {
10164 * placeholder: 'Username'
10166 * var input2 = new OO.ui.TextInputWidget( {
10167 * placeholder: 'Password',
10170 * var submit = new OO.ui.ButtonInputWidget( {
10174 * var fieldset = new OO.ui.FieldsetLayout( {
10175 * label: 'A form layout'
10177 * fieldset.addItems( [
10178 * new OO.ui.FieldLayout( input1, {
10179 * label: 'Username',
10182 * new OO.ui.FieldLayout( input2, {
10183 * label: 'Password',
10186 * new OO.ui.FieldLayout( submit )
10188 * var form = new OO.ui.FormLayout( {
10189 * items: [ fieldset ],
10190 * action: '/api/formhandler',
10193 * $( 'body' ).append( form.$element );
10196 * @extends OO.ui.Layout
10197 * @mixins OO.ui.mixin.GroupElement
10200 * @param {Object} [config] Configuration options
10201 * @cfg {string} [method] HTML form `method` attribute
10202 * @cfg {string} [action] HTML form `action` attribute
10203 * @cfg {string} [enctype] HTML form `enctype` attribute
10204 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
10206 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
10209 // Configuration initialization
10210 config
= config
|| {};
10212 // Parent constructor
10213 OO
.ui
.FormLayout
.parent
.call( this, config
);
10215 // Mixin constructors
10216 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10219 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
10221 // Make sure the action is safe
10222 action
= config
.action
;
10223 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
10224 action
= './' + action
;
10229 .addClass( 'oo-ui-formLayout' )
10231 method
: config
.method
,
10233 enctype
: config
.enctype
10235 if ( Array
.isArray( config
.items
) ) {
10236 this.addItems( config
.items
);
10242 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
10243 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
10248 * A 'submit' event is emitted when the form is submitted.
10253 /* Static Properties */
10255 OO
.ui
.FormLayout
.static.tagName
= 'form';
10260 * Handle form submit events.
10263 * @param {jQuery.Event} e Submit event
10266 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
10267 if ( this.emit( 'submit' ) ) {
10273 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
10274 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
10277 * // Example of a panel layout
10278 * var panel = new OO.ui.PanelLayout( {
10282 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
10284 * $( 'body' ).append( panel.$element );
10287 * @extends OO.ui.Layout
10290 * @param {Object} [config] Configuration options
10291 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
10292 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
10293 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
10294 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
10296 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
10297 // Configuration initialization
10298 config
= $.extend( {
10305 // Parent constructor
10306 OO
.ui
.PanelLayout
.parent
.call( this, config
);
10309 this.$element
.addClass( 'oo-ui-panelLayout' );
10310 if ( config
.scrollable
) {
10311 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
10313 if ( config
.padded
) {
10314 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
10316 if ( config
.expanded
) {
10317 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
10319 if ( config
.framed
) {
10320 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
10326 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
10331 * Focus the panel layout
10333 * The default implementation just focuses the first focusable element in the panel
10335 OO
.ui
.PanelLayout
.prototype.focus = function () {
10336 OO
.ui
.findFocusable( this.$element
).focus();
10340 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
10341 * items), with small margins between them. Convenient when you need to put a number of block-level
10342 * widgets on a single line next to each other.
10344 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
10347 * // HorizontalLayout with a text input and a label
10348 * var layout = new OO.ui.HorizontalLayout( {
10350 * new OO.ui.LabelWidget( { label: 'Label' } ),
10351 * new OO.ui.TextInputWidget( { value: 'Text' } )
10354 * $( 'body' ).append( layout.$element );
10357 * @extends OO.ui.Layout
10358 * @mixins OO.ui.mixin.GroupElement
10361 * @param {Object} [config] Configuration options
10362 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
10364 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
10365 // Configuration initialization
10366 config
= config
|| {};
10368 // Parent constructor
10369 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
10371 // Mixin constructors
10372 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
10375 this.$element
.addClass( 'oo-ui-horizontalLayout' );
10376 if ( Array
.isArray( config
.items
) ) {
10377 this.addItems( config
.items
);
10383 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
10384 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);